3

I am plotting a pie chart with R plotly which I want to slice the pie based on column A and color each slice based on column B. I want each slice to show label based on column A, and I want the legend to be based on the color and column B.

The following is as far as I managed to get. Is there any ways to have the pie from the first plot but the legend from the second? This is my first post on Stackoverflow so please correct me if I did anything wrong. Thanks!

df <- data.frame(columnA = c("Mary", "Tom", "Yumi", "Bernie", "Mew2"),
                                 columnB = c("Female", "Male", "Female", "Male", "Unknown"),
                                 color = c("#627351","#aa44dd","#627351","#aa44dd", "#129333"),
                                 value = c(12,32,5,11,20)
)

# I want a pie like this
plot_ly(df,
                type = "pie",
                labels = ~columnA,
                values = ~value,
                text = ~columnA,
                textposition = 'inside',
                textinfo = 'text+percent',
                insidetextfont = list(color = '#FFFFFF'),
                hoverinfo = 'text',
                legendgroup = ~columnB,
                showlegend = TRUE,
                marker = list(colors = ~color,
                                            line = list(color = '#FFFFFF', width = 1))
) 

# but I want a legend like this
plot_ly(df,
                type = "pie",
                labels = ~columnB,
                values = ~value,
                text = ~columnA,
                textposition = 'inside',
                textinfo = 'text+percent',
                insidetextfont = list(color = '#FFFFFF'),
                hoverinfo = 'text',
                legendgroup = ~columnB,
                showlegend = TRUE,
                marker = list(colors = ~color,
                                            line = list(color = '#FFFFFF', width = 1))
) 

0

Browse other questions tagged or ask your own question.