Stacked bar chart in loop


Hi all,

I am trying to create stacked bar charts with annotations in a loop, as I have multiple columns to represent.
It seems that the y value at add trace doesn’t change, but everything else does. I saw that one issue might be the evaluation, but this is not allowed in a bar object.

My code is:
for (i in 1:n) {
p <- add_trace(evaluation= TRUE, p, y = ~y2[i,], name = y2_name[i],
marker = list(color = y2_color[i],
line = list(color = y2_color[i],
width = 3)))

the issue is y2[i,] , which is 2 vectors merged through rbind.

Any thoughts?



Hi Ana,

See below.

#First create the chart
chart <- plot_ly(type = ‘bar’,
hoverinfo = ‘x+y’)%>%

#Then define the layout. You can’t do it after the loop
layout(title = NULL,
xaxis = list(title = x_axis_title, type = ‘categorical’, nticks = 10, categoryorder = ‘trace’),
yaxis = list(title = ‘’),
barmode = ‘stack’,
paper_bgcolor = white,
plot_bgcolor = white,
font = font_regular,
margin = list(b = 100),
showlegend = TRUE)

#then use the loop to add traces.
for (i in 1:nrow(clientlist)){
client <- clientlist[i,]
chart <- add_trace(chart,
x = ~data$date,
y = ~data[[client]],
name = paste0(’’,
sum(data[[client]]), ’ (’, round(((100/total)*sum(data[[client]])), 1),’%):
', gsub("_", " ", client)), marker = list(color = pal[i]))


variable clientlist is a list of client names. The data contains rows with aggregated data for each week. The columns contain the clients. The client list is used to look up a specific column in the data. So this example creates a stacked bar (of clients) per week.


Hi Franck,

Thanks a lot for sharing your code - it worked, I only needed to transpose my data and add the annotations.

Awesome work.




You’re welcome.

I have looked at your specific code better now. Removing the tilde would also do the job!

So: y = y2[i,]