2016-09-13 41 views
1

我想在添加两个因子的闪亮应用程序中呈现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) 

enter image description here

现在,我尝试添加另一变量来改变边界(红色例如,但可能是因为这是不可能的),或者不透明度。重要的是,我不想更改图例或整体分组。只添加红线或添加不透明度到一些酒吧。

所以,我想补充一些数据:

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条显示有一个更厚的边框: enter image description here

回答

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) 

其中给出:

enter image description here


更新:

如果你想控制不透明度,而不是,我想你可以用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))) 

enter image description here

虽然传说仍然要使用这种方法的一个问题。

+0

不错。是否还有一种解决方法来获得像第一个图中的图例,因此只包含组因子'C'的图例。以及如何设置不透明度而不是边界? – Jimbou

+0

@Jimbou看看更新。 –

+0

非常感谢。我会接受答案,虽然传奇仍然存在问题。 – Jimbou