1
votes

i am trying to figure out how to change text position of labels in pie chart or make it more readable (?). Below is a screenshot of an example and reproducible code:

enter image description here

df <- data.frame(Gruppierung = c("Very long label", "Very very long label", "Long label", "Short label", "Long label / long label"), 
                     freq = c(3.1, 6.2, 8.7, 20, 21))

library(plotly)                                                                                                                                                                       
plot_ly(df, labels=~Gruppierung,values=~freq, marker = list(line = list(color = '#FFFFFF', width = 1)), type="pie",
        textposition = 'auto',textinfo = 'text',
        hoverinfo = 'text',source = "subset",
        text=~paste(sub(" ","<br>",Gruppierung),":","<br>",paste0(freq,"%") ),
        insidetextfont = list(color = '#FFFFFF')) %>%
  layout(showlegend = FALSE,separators = ',.') %>% config(displayModeBar = F)

My Problem (what i would like to achieve):

If Label cannot match horizontally the space that it is in, then it should be positioned outside the pie chart

Thanks for help!

[!!] Approach suggested by @Saurabh Chauhan is very good BUT unfortunatelly it would not match every time, here is a screenshot below which could Show the Problem when even with high freq some Labels are not horizontal:

enter image description here

1

1 Answers

1
votes

The easiest way is to check the freq. If freq is less than some value for example less than 5% then label should positioned outside as follow:

plot_ly(df, labels=~Gruppierung,values=~freq, marker = list(line = list(color = '#FFFFFF', width = 1)), type="pie",
    textposition = ifelse(df$freq<5,"outside","inside"),textinfo = 'text',
    hoverinfo = 'text',source = "subset",
    text=~paste(sub(" ","<br>",Gruppierung),":","<br>",paste0(freq,"%") ),
    insidetextfont = list(color = '#FFFFFF')) %>%
    layout(showlegend = FALSE,separators = ',.') %>% config(displayModeBar = F)

Screenshot from working demo:

enter image description here

Updated

One more result with (when freq<10): enter image description here