Search code examples
rplotplotlybar-chartr-plotly

Combine "grouped" and "stacked" bars


I am trying to combine a stacked bar and a simple grouped bar on one X axis in R-plotly. Here is a reproducible sample of code I am using:

library(data.table)
library(magrittr)
library(plotly)

DT <- data.frame("year" = c(2019, 2020, 2021),
             "example_var1" = c(12872100, 69436460, 8129560),
             "example_var2" = c(25589160, 19671712, 19648085),
             "example_var3" = c(15889160, 27671712, 19648085))
setDT(DT)
DT <- melt(DT, id.vars = "year")
DT[, ratio := paste0(round(value / sum(value) * 100, digits = 0), "%"), by = year]

# I would like to select 'example_var1' and 'example_var2 ' only for this part
my_plot <-
    plot_ly(
        DT,
        x = ~ year,
        y = ~  value, # select 'example_var1' and 'example_var2'
        type = "bar",
        name = ~ variable,
        text = ~ ratio,
        textposition = 'auto'
    ) %>%
    layout (barmode = "stack")

# I would like to select 'example_var3' only for this part
my_plot <- my_plot %>%
    add_trace(
        x = ~ year,
        y = ~ value,  # select 'example_var2'
        type = "bar",
        name = ~ variable,
        text = ~ ratio,
        textposition = 'auto'
    ) %>%
    layout (barmode = "group")
  1. I don't know how to plot a serie of a stacked bar and a group bar in one plot using the same X axis.

  2. I can't find a way to determine that variables "example_var1" and "example_var2" should plotted together on a stacked bar and variable "example_var3" should be plotted separately as a group bar.

Below a plot that I would like to get:

enter image description here


Solution

  • I am not aware of a straightforward solution for this (read more here: Combination of grouped and stacked bar chart ). But we can find a workaround by editing the data and modifying the axis. See below;

    DT1 <- DT[variable =="example_var3", year := year + 0.4][]
    
    my_plot <-
     plot_ly(
       DT1,
       x = ~ year,
       y = ~  value,
       type = "bar",
       name = ~ variable,
       text = ~ ratio,
       textposition = 'auto'
     ) %>%
     layout (barmode = "stack",
             xaxis = list(
               ticktext = list(2019, 2020, 2021),
               tickvals = lapply(list(2019, 2020, 2021), `+`, 0.2),
               tickmode = "array"
             ))