'How to add percentage labels in a stacked bar keeping bars heights (R plotly)
I am creating a stack bar in plotly. Each bar represents one year. I would like to keep heights of the bars and add labels representing share of a variable in a particular year (I would like a sum of percentages to be equal 100% for each bar).
Below a reproducible sample of code I am working with:
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
This is what I would like to get:

Any hint will be much appreciated. Thank you!
Solution 1:[1]
I'd reshape the data.frame to long format to calculate the percantage and to avoid the loop:
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |


