Skip to content

No way to make legend order exactly match bar order in relative stacked bar plot #1694

@dracodoc

Description

@dracodoc

Sometimes we want to plot negative values below x axis in a stacked bar plot. This can be done with barmode as "relative".

Further, I want to make the legend order exactly match the bar order in plot. However the positive bars stack from middle to top, negative bars stack from middle to down, thus no matter how I arrange the variable levels, there is no way to make the legend order exactly match bar order.

library(plotly)
library(data.table)

set.seed(42)
dt_test <- data.table(x = rep(1:5, each = 6), variable = rep(letters[1:6], 5), value = sample(10:40, 30))
dt_test[variable %in% letters[3:5], value := -value]

dt_test[, variable := factor(variable, levels = c("c", "d", "e", "a", "b", "f"))]

plot_ly(dt_test) %>% 
  add_bars(x = ~x, y = ~value, color = ~variable) %>%
  layout(barmode = 'relative', legend = list(traceorder = "reversed"))

image

I'm not sure how this can be done, unless we

  • change the stack order in negative part as bottom up
  • or can arrange legend order freely without changing bar stack order

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions