【问题标题】:Plotly Bar chart, add a second factor for coloring, opacity or border colorPlotly 条形图,为着色、不透明度或边框颜色添加第二个因素
【发布时间】:2017-01-21 07:45:40
【问题描述】:

我想在闪亮的应用程序中呈现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 的条形显示为更粗的边框:

【问题讨论】:

    标签: r shiny bar-chart plotly


    【解决方案1】:

    你可以试试:

    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)))
    

    虽然图例使用这种方法仍然会成为问题。

    【讨论】:

    • 不错。是否还有一种解决方法来获得像第一个情节中的图例,因此图例仅包含组因子“C”。以及如何设置不透明度而不是边框​​?
    • 非常感谢。我会接受这个答案,虽然传说还是有问题。
    猜你喜欢
    • 2021-07-26
    • 2022-11-04
    • 1970-01-01
    • 2018-04-01
    • 2015-03-09
    • 1970-01-01
    • 1970-01-01
    • 2014-10-02
    • 2020-09-05
    相关资源
    最近更新 更多