Home > database >  How to reverse bars order on plotly stacked bar
How to reverse bars order on plotly stacked bar

Time:08-02

I am creating a simple stacked bar plot in plotly

set.seed(1)
data <- data.frame(period = rep(seq(1:4), times =2),
                   variable = rep(c("variable 1", "variable 2"), each = 4),
                   value = runif(8))


fig <-
    plot_ly(data,
            x = data$period,
            y = ~ data$value,
            type = "bar",
            name = data$variable
    ) %>%
    layout (barmode = "stack")
fig

I would like to reverse the bars (I would like "variable 1" and its legend entry to be on the top, "variable 2 should be on the bottom both on the plot and in the legend). I was trying to achieve that by arranging "variable" column in "data" data frame but this did not help:

set.seed(1)
data <- data.frame(period = rep(seq(1:4), times =2),
                   variable = rep(c("variable 1", "variable 2"), each = 4),
                   value = runif(8)) %>%
    dplyr::arrange(desc(variable))


fig <-
    plot_ly(data,
            x = data$period,
            y = ~ data$value,
            type = "bar",
            name = data$variable
    ) %>%
    layout (barmode = "stack")
fig

How can I manipulate order of legend entries and bars order on a stacked bar in plotly? Any help would be much appreciated. Thank you!

CodePudding user response:

You could do this by changing the order levels of your variable in a factor. So using this factor(data$variable, levels = c("variable 2", "variable 1")) will reverse the order of your stacked barplot like this:

library(plotly)
set.seed(1)
data <- data.frame(period = rep(seq(1:4), times =2),
                   variable = rep(c("variable 1", "variable 2"), each = 4),
                   value = runif(8))

data$variable <- factor(data$variable, levels = c("variable 2", "variable 1"))

fig <-
  plot_ly(data,
          x = data$period,
          y = ~ data$value,
          type = "bar",
          name = data$variable
  ) %>%
  layout (barmode = "stack")
fig

Created on 2022-08-01 by the reprex package (v2.0.1)

  • Related