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