Customize legend entries in pie chart using R Plotly

I am trying to make a pie chart in R using plotly. I have a tibble (df) with 4 columns - (1) an observation (x), (2) value of the observation (y), (3) category of the observation (cat), and (4) color of each observation (colors). Colors are unique for each category (every observation within the same category will share the same color). I need each segment of the pie chart to represent each observation with the size of the segment corresponding to the value of the observation. I also need the segments to be colored by their unique category color. I have been able to build such a pie chart.

I am, however, struggling with how to customize the legend. Using showlegend=TRUE shows each observation with it's color. I need the legend to showcase each unique category with its distinct color. I would really appreciate it if someone could help me out with this.

Here is some dummy code that models this problem -

# Load packages
suppressWarnings(suppressMessages(library(tidyverse)))
suppressWarnings(suppressMessages(library(plotly)))

# Initialize variables
df = NULL
x = c("apple", "John", "dog", "lion", "strawberry", "Liz", 
      "cat", "peach", "banana", "elephant", "pear", "tiger")
y = c(1, 1, 3, 5, 4, 3, 6, 4, 1, 2, 1, 6)
cat = c("fruit", "person", "animal", "animal", "fruit", "person", 
        "animal", "fruit", "fruit", "animal", "fruit", "animal")
colors = NULL

# Define colors
for (i in 1:length(cat)) {
    if (cat[i] == "fruit") {
        color = "#FFD700"
    } else if (cat[i] == "animal") {
        color = "#FB8072"
    } else {
        color = "#D3D3D3"
    }
    colors = c(colors, color)
}

# Create data frame
df = as_tibble(cbind(x, y, cat, colors))

# Sort data frame
df = df[order(df$cat, df$x), ]

# Define colors for pie chart
pie_colors = as.character(df$colors)

# Define margins for pie chart
margins = list(l=50, r=50, b=125, t=125)

# Build the pie chart
pie_plt = plot_ly(data=df,
                 values=~y,
                 labels=~x,
                 type="pie",
                 textinfo="label+percent",
                 sort=FALSE,
                 marker=list(colors=pie_colors,
                            line=list(color="black", width=1))) %>%
            layout(autosize=FALSE, margin=margins, showlegend=TRUE)

# Show the pie chart
pie_plt

can you provide a reprex.
i.e.

dput(df)

Hi @nirgrahamuk, I have edited the post and provided a reprex. Let me know if this is sufficient.

Thanks, its a good reprex.
Unfortunately, I tried a few ideas, and couldnt get any closer. I'm afraid plotly may not support the required behaviour

1 Like

Hi, I'm not sure if you found a way to solve this yet, but what I did, is that, since you can specify the info shown in "textinfo" is that I would simply add the category to that data. Something similar to:

summrsd_Vtas_Kg_Fam_Can_pie2<- Dataset_Ventas_por_Familia_SubFam_Canal_Subcan1%>%
dplyr::group_by(Familia)%>%
dplyr::summarize(ValorNeto=sum(ValorNeto))%>%
mutate(text = paste("Subfamilia: ", Familia, "\nValor neto: ", ValorNeto, sep=""))

Pievis_Fam <-plot_ly(summrsd_Vtas_Kg_Fam_Can_pie2,
labels= ~Familia,
values= ~ValorNeto,
type='pie',
textinfo = 'label+percent+text',
marker = list(colors = c('#1f5bb4', '#1f76b4','#1f8cb4','#1f9eb4', '#1fb4b4', '#1fb4a5')),
hoverinfo = 'text', text = summrsd_Vtas_Kg_Fam_Can_pie2$text,
showlegend = FALSE
)
Pievis_Fam

Pay special attention to the "text" column in my dataset, and how it's added to the textinfo label.

Regards.

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.