不使用add_trace时,条形图中缺少标签颜色

时间:2017-01-02 18:01:54

标签: r plotly

在不使用add_trace的情况下创建彩色条形图时,图例中的某些标签颜色仍为黑色:

colors <- c("blue","grey", "red", "yellow")
  data <- data.frame(time = factor(c("2010", "2011", "2010", "2011", "2010", "2011")),
                     value = c(10, 20, 30, 40, 50, 60),
                     type = c("A", "B", "C", "A", "B", "C"))

  data %>%
    plot_ly(
      type = "bar",
      x = ~time,
      y = ~value,
      color =  ~type,
      colors = colors) %>%
    layout(barmode = "relative")

使用&#34; marker = list(color = colors)&#34;时可以发现同样的问题。选项而不是颜色选项直接。当使用add_trace时,一切似乎都运行正常。但由于颜色级别的数量一直未提前知道,因此使用add_trace(在循环内)的解决方案感觉不方便。

2 个答案:

答案 0 :(得分:0)

试试这个:

h<-ggplot(data, aes(x=time, y=value, fill=type))+geom_bar(stat = "identity")
ggplotly()

答案 1 :(得分:0)

作为替代方案,也许您可​​以将数据集从长到大重新整形。

以下是代码:

library(reshape2)
data_wide <- dcast(data, time ~ type, value.var="value")
plot_ly(data_wide, x=~time) %>% 
      add_bars(y = ~A, name = "A", color= I("blue")) %>% 
      add_bars(y = ~B, name = "B", color= I("red")) %>%
      add_bars(y = ~C, name = "C", color= I("yellow")) %>% 
      layout(barmode = "stack", yaxis = list(title ="value"))