Plotly (R) - 饼图:如何固定每组的颜色分配颜色?

Plotly (R) - Pie chart: How to fixate the color assignment color per group?

我们正在构建一个闪亮的应用程序,我们在其中使用了动态绘图饼图。用户可以 select 变量包含在图中。

添加自定义颜色代码允许我添加自定义颜色,但它们不会像在绘图条形图中那样(使用颜色命令)坚持分组变量。

示例:

library(plotly)

dat <- data.frame(dis = c(1,2,3), value = c(20,30,24))

plot_ly(dat, labels = ~dis, values = ~value, sort = F, 
        marker = list(colors = c("1" = "#B76C9E", 
                                 "2" = "#4285F4",
                                 "3" = "#EA4335"))) %>%
  add_pie(hole = 0.3) %>%
  layout(legend = list(orientation = 'h'), margin = list(l = 0 , r = 0, t = 0, b = 100, pad = 1),
         yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))

但是当我从 data.frame 中删除 dis == 1 时(就像我的用户将在 Shiny 应用程序中所做的那样)颜色会发生变化并且不会保持其指定的颜色:

dat2 <- data.frame(dis = c(2,3), value = c(30,24))

plot_ly(dat2, labels = ~dis, values = ~value, sort = F, 
        marker = list(colors = c("1" = "#B76C9E", 
                                 "2" = "#4285F4",
                                 "3" = "#EA4335"))) %>%
  add_pie(hole = 0.3) %>%
  layout(legend = list(orientation = 'h'), margin = list(l = 0 , r = 0, t = 0, b = 100, pad = 1),
         yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))

有没有办法将颜色锁定到分类变量,以便“2”始终获得相同的颜色?

我猜你必须通过更新调用中的颜色,像这样..但我认为它很粗糙:

pal = c("#B76C9E", "#4285F4","#EA4335")
names(pal) = as.character(1:3)

updated_pal = pal[unique(as.character(dat2$dis))]

plot_ly(dat2, 
labels = ~dis, values = ~value, sort = F,
marker=list(colors=updated_pal)) %>%
  add_pie(hole = 0.3) %>%
  layout(legend = list(orientation = 'h'), margin = list(l = 0 , r = 0, t = 0, b = 100, pad = 1),
         yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))