【问题标题】:Plotly stacked barchart - not correct colors in legend堆积条形图 - 图例中的颜色不正确
【发布时间】:2017-04-29 14:21:45
【问题描述】:

我正在尝试根据此处的数据在plotly (plotly_4.5.6) 中绘制堆积条形图:

> dane
visit_source variable value
1      organic     2016    32
2       social     2016    20
3           hp     2016    24
4      branded     2016    24
5      organic     2015    25
6       social     2015    25
7           hp     2015    25
8      branded     2015    25

使用此代码:

library("dplyr")
library("plotly")

plot_ly(dane, y = ~variable, x = ~value, color = ~visit_source, text = ~paste0(value, "%"),
        type = "bar", hoverinfo = "text+name", marker = list(line = list(color = "white", width = 2))) %>%
    layout(barmode = "stack",
           legend = list(orientation = "h"),
           xaxis = list(ticksuffix = "%"),
           yaxis = list(title = ""))

我明白了:

但是当我稍微修改我的data.frame(只去掉一行)时,图例中的一些颜色变成了黑色。喜欢这里:

plot_ly(dane[-1, ], y = ~variable, x = ~value, color = ~visit_source, text = ~paste0(value, "%"),
        type = "bar", hoverinfo = "text+name", marker = list(line = list(color = "white", width = 2))) %>%
    layout(barmode = "stack",
           legend = list(orientation = "h"),
           xaxis = list(ticksuffix = "%"),
           yaxis = list(title = ""))

当我为每个year 拥有visit_source 的所有levelsvalue 等于0 时,它会起作用,但也会出现在hover 中,这是我不喜欢的。

你知道这里有什么问题吗?感谢您的帮助!

我的数据:

structure(list(visit_source = structure(c(1L, 2L, 3L, 4L, 1L, 
                                          2L, 3L, 4L), .Label = c("organic", "social", "hp", "branded"), class = "factor"), 
               variable = c("2016", "2016", "2016", "2016", "2015", "2015", 
                            "2015", "2015"), value = c(32, 20, 24, 24, 25, 25, 25, 25
                            )), class = "data.frame", .Names = c("visit_source", "variable", 
                                                                 "value"), row.names = c(NA, -8L)) -> dane

【问题讨论】:

  • 发生了一些奇怪的事情,因为dane[c(-1, -5), ] 产生了一个好的结果(缺少一个级别)。如果你制作一个ggplot并使用ggplotly,它会产生一个OK的结果。
  • 可能是一个错误。正如@RomanLuštrik 提到的,如果你完全放弃“有机”级别,它会产生正确的结果......

标签: r bar-chart plotly


【解决方案1】:

尝试安装Plotly (4.5.6.9000) 的最新开发者版本,它应该可以工作

df = data.frame(visit_source=c('organic', 'social', 'hp', 'branded', 'organic', 'social', 'hp', 'branded'), 
                variable = c(rep('2016', 4), rep('2015',4)),
                value=c(32, 20, 24, 24, 25, 25, 25, 25))


library("dplyr")
library("plotly")

plot_ly(df[-1,], y = ~variable, x = ~value, color = ~visit_source, text = ~paste0(value, "%"),
        type = "bar", hoverinfo = "text+name", marker = list(line = list(color = "white", width = 2))) %>%
  layout(barmode = "stack",
         legend = list(orientation = "h"),
         xaxis = list(ticksuffix = "%"),
         yaxis = list(title = ""))

【讨论】:

    猜你喜欢
    • 2017-10-19
    • 1970-01-01
    • 2017-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-02
    相关资源
    最近更新 更多