Black Lives Matter. Please consider donating to Black Girls Code today.

Extending the basic stacked bar chart example

I’m trying to create a stacked bar chart with only one bar and several y values contributing to the bar. Looking at the basic example in the bar charts section of the docs, the bars are built step by step adding one y value after another, like this:

p <- plot_ly(x = c(“giraffes”, “orangutans”, “monkeys”), y = c(20, 14, 23), name = “SF Zoo”, type = “bar”, filename=“r-docs/simple-bar”)
p2 <- add_trace(p, x = c(“giraffes”, “orangutans”, “monkeys”), y = c(12, 18, 29), name = “LA Zoo”, filename=“r-docs/simple-bars”)
layout(p2, barmode = “stack”)

This example has two (sets of) y values (SF Zoo, LA Zoo). Now, if I want to add more y values, do I have to call add_trace for every y? E.g. if my data looks like this:

foo <- data.frame(names=c(“Apples”, “Bananas”, “Strawberries”, “Oranges”), values=c(.3, .15, .4, .5))

and I want all the rows of foo to get stacked on one bar, how can I add the whole data.frame in one function call (plot_ly or add_trace)? I’ve tried several ways and searched the docs without finding a solution. Any advise is much appreciated.

So the stacked bar charts will stack y values for the same categories. Because you’re using R it’s probably possible to do this programatically with a for loop instead of writing it out each time.