Plotly 条形图,为着色、不透明度或边框颜色添加第二个因素

Plotly Bar chart, add a second factor for coloring, opacity or border color

我想在添加两个因素的闪亮应用程序中呈现 plotly 条形图。 一个因素没问题,第二个就麻烦了。而且我不确定它是否可能。

这是一些数据。 C 是分组或着色的分组因子。这是相对容易和直接的。

set.seed(123)
df <- data.frame(A=letters[1:5],B=runif(5),C=sample(1:3,5,replace = T))
df <- df[order(df$B, decreasing = T),]
df
  A         B C
5 e 0.9404673 2
4 d 0.8830174 2
2 b 0.7883051 2
3 c 0.4089769 3
1 a 0.2875775 1

library(plotly)
plot_ly(df, type = "bar", x = A, y = B,  group = C)

现在我正在尝试添加另一个变量来更改边框(例如,红色,但可能这是不可能的)或不透明度。重要的是,我不想更改图例或整体分组。仅添加一条红线或为某些条添加不透明度。

所以,我添加一些数据:

df$D <- c(0.2, 1, 0.2, 1, 0.2)

但我尝试过的所有方法都不起作用。

plot_ly(df, type = "bar", x = A, y = B,  color = as.factor(C)) # similar, but different order
plot_ly(df, type = "bar", x = A, y = B,  group = as.factor(C)) # same order, other colors
plot_ly(df, type = "bar", x = A, y = B,  group = C, color = as.factor(C)) #adds a second group
plot_ly(df, type = "bar", x = A, y = B,  group = C, opacity = as.factor(D)) # no idea whats happening
plot_ly(df, type = "bar", x = A, y = B,  color = as.factor(C), opacity = as.factor(D)) # the opacity of e is wrong

你有什么想法可以同时使用 interaction()plotly::add_trace() 或其他方法来解决问题吗?

我的预期输出,带有 D==0.2 的条显示为更粗的边框:

你可以试试:

df %>% 
  plot_ly(x = A, y = B, type = "bar", group = C, 
          marker = list(line = list(width = ifelse(D == 0.2, 10, NA), 
                                    color = ifelse(D == 0.2, "red", NA))),
          showlegend = FALSE)

给出:


更新:

如果你想控制不透明度,我想你可以玩 toRGB():

cols <- RColorBrewer::brewer.pal(length(unique(df$C)), name = "Set1")
df$color <- factor(df$C, labels = cols)

df %>% 
  plot_ly(x = A, y = B, type = "bar",
          marker = list(color = toRGB(color, alpha = D)))

虽然图例使用这种方法仍然是个问题。