Reputation: 41
I need to be able to sort a stacked bar graph based on the numeric y values in each stack. There seems to be a solution in the R version of Plotly that handles this problem, but I haven't found one for Python yet, or more specifically, Plotly Dash.
Here are two example of how this problem of sorting can be solved in R:
1) Stacked bar graphs in plotly: how to control the order of bars in each stack
Here's basic code for a Plotly stacked bar chart:
import plotly.plotly as py
import plotly.graph_objs as go
trace1 = go.Bar(
x=['giraffes', 'orangutans', 'monkeys'],
y=[20, 14, 23],
name='SF Zoo'
)
trace2 = go.Bar(
x=['giraffes', 'orangutans', 'monkeys'],
y=[12, 18, 29],
name='LA Zoo'
)
data = [trace1, trace2]
layout = go.Layout(
barmode='stack',
)
fig = go.Figure(data=data, layout=layout)
py.iplot(fig, filename='stacked-bar')
Here's the actual output:
https://i.sstatic.net/ZXpuf.png
Sorting these bars based on the x axis (categorical) is easy. The only code needed to sort x alphabetically would be:
layout = go.Layout(
barmode='stack',
xaxis={'categoryorder': 'category ascending'}
)
But is it possible to also sort each stack by numeric y values with Plotly Dash (Python)? Here is what the expected result would be if each stacked bar were sorted such that the lowest y value within each stacked bar is at the bottom of bar (regardless of trace):
https://i.sstatic.net/4wEzn.png
Right now it seems like only categories can be sorted.
Upvotes: 4
Views: 1979
Reputation: 693
Just switch the order of the traces. Plotly plots the traces, and shows the legend based on the order in which you write the traces.
Upvotes: 0