调整堆积条形图中的顺序

时间:2019-09-06 15:18:10

标签: r plotly

是否可以调整plotly中堆积的条形图的顺序?采取以下MWE:

library(plotly)

df <- data.frame(date = rep(seq.Date(as.Date("8/15/2018", "%m/%d/%Y"), as.Date("10/15/2018", "%m/%d/%Y"), by = "1 month"), 2),
                 variable = c(rep("under", 3), rep("over", 3)),
                 value = c(rep(5, 3), rep(1, 3)))

plot_ly(df) %>%
  add_trace(x = ~date, y = ~value, color = ~variable, name = "variable", type = "bar") %>%
  layout(barmode = "stack")

哪种产量:

enter image description here

但是,我希望将较小的部分放在顶部。我尝试重新排序因素:

df$variable <- factor(df$variable, levels = c("under", "over"))

但这只会改变颜色:

enter image description here

所需的输出

enter image description here

这可能吗? 请注意,我需要使用 add_trace 进行绘制,因为我实际制作的图形包括其他线图。

1 个答案:

答案 0 :(得分:0)

我通过在add_trace调用中子设置数据帧找到了一种解决方法。如果有人有更雄辩的答案,将不胜感激。

plot_ly(df) %>%
  add_trace(data = df[df$variable=="under",], x = ~date, y = ~value, color = ~variable, name = "under", type = "bar") %>%
  add_trace(data = df[df$variable=="over",], x = ~date, y = ~value, color = ~variable, name = "over", type = "bar") %>%
  layout(barmode = "stack")