Sphere
Log in Join
☆ 8

seaborn catplot ordering categories alphabetically not logically

seaborn 0.13.2, Python. I have a categorical column 'size' with values ['small', 'medium', 'large', 'xlarge'] but seaborn's catplot/barplot plots them alphabetically: large, medium, small, xlarge. I want the logical order. I tried setting the column as pandas Categorical with categories in the right order, and it works for barplot but catplot with col= still seems to use alphabetical somewhere. Also the legend order is wrong. What's the clean way to control category order across seaborn functions?

⚑ Report

4 replies

☆ 0
S so ·2026-11-12#1

Two things: for the axis order pass order=['small','medium','large','xlarge'] to barplot/countplot, and for facet grids (catplot with col=) pass category_order= (in recent seaborn) or set the column as an ordered pandas Categorical before plotting - catplot respects the Categorical's order for facets. For legend/hue order use hue_order=[...]. Seaborn 0.13 changed some of these parameters, so check which your version uses.

⚑ Report
☆ 0
G ghost ·2026-11-15#2

Passing order= fixed the barplot. For catplot the parameter is category_order in 0.13 - I set that and the panels are in the right order. Still fighting the legend: hue_order works for hue but the facet labels (the little titles above each panel) were alphabetical until I made the column an ordered Categorical. So both were needed. Is there a single source of truth so I don't have to specify order in three places?

⚑ Report
☆ 0
O offbyone ·2026-11-18#3

The ordered pandas Categorical is that source of truth - if you convert once with pd.Categorical(df['size'], categories=[...], ordered=True), most seaborn functions pick up the order automatically. But some still want explicit order/hue_order, so in practice you often pass both. A helper function that sets the order once and applies it consistently is reasonable. Just don't fight it by sorting the DataFrame - sorting rows doesn't change seaborn's categorical ordering.

⚑ Report
☆ 0
C cache ·2026-11-20#4

Ended up making the ordered Categorical once at data-load time and passing order/hue_order from a shared list constant. Now all charts are consistent. The gotcha: catplot facet labels needed the Categorical dtype specifically, not just the category_order param - so convert the dtype AND pass the params. Seaborn's ordering is one of those things that's simple once you know which lever each function responds to.

⚑ Report
Log in to reply.