0
votes

Is it possible to adjust the ordering of a stacked bar chart in plotly? Take the following MWE:

library(plotly)

df <- data.frame(date = rep(seq.Date(as.Date("8/15/2018", "%m/%d/%Y"), as.Date("10/15/2018", "%m/%d/%Y"), by = "1 month"), 2),
                 variable = c(rep("under", 3), rep("over", 3)),
                 value = c(rep(5, 3), rep(1, 3)))

plot_ly(df) %>%
  add_trace(x = ~date, y = ~value, color = ~variable, name = "variable", type = "bar") %>%
  layout(barmode = "stack")

Which yields:

enter image description here

However, I would like the smaller portion to be on top. I've tried re-ordering the factor:

df$variable <- factor(df$variable, levels = c("under", "over"))

But this only changes the color:

enter image description here

Desired output

enter image description here

Is this possible? Note that I need to use add_trace to make the plot because the graph I am actually making includes additional line plots.

1
If I try what you have but change name = "variable" to name = ~variable then your df$variable <- factor(df$variable, levels = c("under", "over")) works perfectly.CrunchyTopping

1 Answers

0
votes

I found a workaround by sub-setting the dataframe within the add_trace call. If anyone has a more eloquent answer it would be greatly appreciated.

plot_ly(df) %>%
  add_trace(data = df[df$variable=="under",], x = ~date, y = ~value, color = ~variable, name = "under", type = "bar") %>%
  add_trace(data = df[df$variable=="over",], x = ~date, y = ~value, color = ~variable, name = "over", type = "bar") %>%
  layout(barmode = "stack")