plotly / plotly/plotly.R

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

Open
#1,694 2 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
R
Stars
2.7k
Forks
641
PR merge metrics
No merged PRs in 30d

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the supplied R example with plot_ly(), add_bars(), barmode = "relative", and the current legend setting. Investigate whether the requested behavior can be supported for negative and positive stacks; done means the legend order exactly matches the visible bar order, or the limitation and chosen ordering behavior are documented.

Written by the indexing model from the issue text.

Assessment

Tech stack
r
Domain
data-visualization
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.