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

Rom*_*man 4 r bar-chart shiny plotly

我想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)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

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

所以,我添加一些数据:

df$D <- c(0.2, 1, 0.2, 1, 0.2)
Run Code Online (Sandbox Code Playgroud)

但是我尝试过的一切都不起作用。

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
Run Code Online (Sandbox Code Playgroud)

你有什么想法可以用也许interaction()plotly::add_trace()一起或其他东西来解决问题吗?

我的预期输出,D==0.2带有更粗边框的条形显示: 在此处输入图片说明

Ste*_*pré 6

你可以试试:

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)
Run Code Online (Sandbox Code Playgroud)

这使:

在此处输入图片说明


更新:

如果你想控制不透明度,我想你可以玩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)))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

尽管使用这种方法图例仍然会是一个问题。