首页 > 解决方案 > 如何使用 R Plotly 在后台将组和堆栈条形图与 layout.shape 结合起来?

问题描述

我正在尝试创建一个需要同时使用堆栈和组条形图的可视化。我使用的数据有数千行,下面是其中的一个子集。

 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

我想要的情节如下所示: 在此处输入图像描述

按 Month 分组按 Cat 堆叠并区分不同的Week我想在背景中添加矩形形状(https://plotly.com/r/shapes/)不同的星期。

提前致谢!

标签: rgraphplotlybar-chartr-plotly

解决方案


如评论中所述,堆叠+分组条形图尚未在 plotly 中实现。这是一个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)

结果


推荐阅读