简体   繁体   中英

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.

Thanks in advance!

As mentioned in the comments stacked+grouped bar charts aren't implemented yet in plotly . Here is a ggplot2 / ggplotly workaround:

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)

结果

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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