2016-09-13 39 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