简体   繁体   English

如何使用 R Plotly 在后台将组和堆栈条形图与 layout.shape 结合起来?

[英]How can I combine group and stack bar chart with layout.shape in background using R Plotly?

I am trying to create a visualization where I need use both stack and group bar charts.我正在尝试创建一个可视化,我需要同时使用堆栈和组条形图。 The data I am using has thousand of rows, the below one is the subset of that.我使用的数据有数千行,下面的数据是其中的一部分。

 Month      Week   Cat   n
_____________________________
 2019-Dec    4      A    17
 2019-Dec    4      B    6
 2019-Dec    5      A    21
 2019-Dec    5      C    10
 2020-Jan    1      A    19
 2020-Jan    1      B    20
 2020-Jan    1      C    12

The plot I want is something like below:我想要的情节如下所示: 在此处输入图片说明

Where it's group by Month , stack by Cat and to distinguish different Week I want to add rectangular shapes in the background ( https://plotly.com/r/shapes/ ) for different weeks.按 Month 分组按 Cat 堆叠并区分不同的Week我想在不同的背景中添加矩形形状( https://plotly.com/r/shapes/ )。

Thanks in advance!提前致谢!

As mentioned in the comments stacked+grouped bar charts aren't implemented yet in plotly .正如评论中提到的,堆叠+分组条形图尚未在 plotly 中实现 Here is a ggplot2 / ggplotly workaround:这是一个ggplot2 / ggplotly解决方法:

library(plotly)
library(ggplot2)

DF <- data.frame(
  stringsAsFactors = FALSE,
             Month = c("2019-Dec","2019-Dec",
                       "2019-Dec","2019-Dec","2020-Jan","2020-Jan","2020-Jan"),
              Week = c(4L, 4L, 5L, 5L, 1L, 1L, 1L),
               Cat = c("A", "B", "A", "C", "A", "B", "C"),
                 n = c(17L, 6L, 21L, 10L, 19L, 20L, 12L)
)

p <- ggplot(DF, aes(x = Week, y = n, fill = Cat)) + geom_bar(stat = 'identity', position = 'stack') + facet_grid( ~ Month) + theme_bw()

ggplotly(p)

结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM