如何在保持条形高度的堆叠条形图中添加百分比标签(R plotly)

How to add percentage labels in a stacked bar keeping bars heights (R plotly)

我正在 plotly 中创建堆栈栏。每个条代表一年。我 想保持条形的高度并添加代表特定年份变量份额的标签(我希望每个条形的百分比总和等于 100%)。

下面是我正在使用的可重现代码示例:

data <- data.frame("year" = c(2019, 2020, 2021),
                   "example_var1" = c(12872100, 69436460, 8129560),
                   "example_var2" = c(25589160, 19671712, 19648085))

vars = c("example_var1", "example_var2")

my_plot <- plot_ly(data, type = "bar")

# a loop is being used as vars names must be dynamic and depend on input data

for (k in vars) {
    
    my_plot <- my_plot %>%
        add_trace(x = ~ year, y = as.formula(paste0("~`", k, "`")), type = "bar", name = k,  text = "", textposition = 'auto') %>%
        layout (barmode = "stack")
}

my_plot

这就是我得到的:

这就是我想要得到的:

任何提示将不胜感激。谢谢!

我将 data.frame 重塑为长格式以计算百分比并避免循环:

library(plotly)
library(data.table)

DT <- data.frame(
  "year" = c(2019, 2020, 2021),
  "example_var1" = c(12872100, 69436460, 8129560),
  "example_var2" = c(25589160, 19671712, 19648085)
)

setDT(DT)
DT <- melt(DT, id.vars = "year")
DT[, ratio := paste0(round(value / sum(value) * 100, digits = 0), "%"), by = year]

my_plot <-
  plot_ly(
    DT,
    x = ~ year,
    y = ~ value,
    type = "bar",
    name = ~ variable,
    text = ~ ratio,
    textposition = 'auto'
  ) %>%
  layout (barmode = "stack")

my_plot