合并 "grouped" 和 "stacked" 条

Combine "grouped" and "stacked" bars

我正在尝试在 R-plotly 中的一个 X 轴上组合堆叠条形图和简单分组条形图。这是我正在使用的可重现的代码示例:

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. 我不知道如何使用相同的 X 轴在一个图中绘制一系列堆叠条形图和组条形图。

  2. 我找不到确定变量“example_var1”和“example_var2”应该一起绘制在堆积条和变量“[=32=”上的方法]" 应该作为一个组条单独绘制。

下面一个我想得到的图:

我不知道对此有直接的解决方案(在此处阅读更多内容: 分组和堆叠条形图的组合 )。但是我们可以通过编辑数据和修改轴来找到解决方法。见下文;

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"
         ))