0

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: enter image description here

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!

ismirsehregal
  • 30,045
  • 5
  • 31
  • 78
Williams86
  • 320
  • 1
  • 11

1 Answers1

2

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)

result

ismirsehregal
  • 30,045
  • 5
  • 31
  • 78