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())
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"])
)
Is there a way to achieve this without changing the input data?