How to change sort order of stacked bar chart using seaborn objects (v0.12)

Viewed 50

I am using seaborn objects to plot a stacked bar chart and I am wondering what the right was is to change the sort order in which the bars are stacked.

Looking at this example:

import seaborn.objects as so
import seaborn as sns

penguins = sns.load_dataset("penguins")
so.Plot(
    penguins,
    x="species",
    y="body_mass_g",
    color="sex",
).add(so.Bar(width=0.2), so.Agg(), so.Stack())

enter image description here the order is ['male', 'female']. How do I reverse that order?

The only answer I came up with is to sort the input data. It appears that the order of the bars depends on the order of appearance in the dataset.

so.Plot(
    penguins.sort_values(by="sex", ascending=True),
    x="species",
    y="body_mass_g",
    color="sex",
).add(so.Bar(width=0.2), so.Agg(), so.Stack()).scale(
    color=so.Nominal(order=["Male", "Female"])
)   

enter image description here

Is there a way to achieve this without changing the input data?

1 Answers

You can define the order for the color variable with a scale:

(
    so.Plot(penguins, x="species", y="body_mass_g", color="sex")
    .add(so.Bar(width=0.2), so.Agg(), so.Stack())
    .scale(color=so.Nominal(order=["Female", "Male"]))  # <--- Add this line
)

enter image description here

It looks like the stack operation is still putting the female bars on top of the male bars, which is interesting and may be a bug, but also may be what you're looking for here (i.e. that the stack order matches the legend order from top-to-bottom). There is an issue to make that happen by default: https://github.com/mwaskom/seaborn/issues/2888

Related