Ordering hues in seaborn
I’ve been making a lot of categorical graphs recently, with both filtered and unfiltered data from single-cell images. My main problem here is controlling the order of the categories, since I want them uniform across all graphs and in the order that I set. This is a little harder than it sounds, since sometimes I need uniform coloring (“hue” in seaborn parlance) and sometimes I need uniform categorical axis order.
After trawling stack overflow for answers, I learned that the pandas api has a tool to handle this: CategoricalDtype. Huzzah! The documentation page really says all that you need to know about it. Setting ordered=True in the data type makes that the default ordering.
from pandas.api.types import CategoricalDtype
cats = CategoricalDtype(categories=categories, ordered=True)
I have a separate pattern that I find useful for declaring color palettes, using the seaborn color_palette function. I always use the “colorblind” palette for categorical data, since it looks nice and is more accessible than the default.
cmap = dict(zip(categories, sns.color_palette("colorblind", categories))
Passing cmap to the palette argument in any seaborn plotting function forces use of the specified hues on the graph.
Every time I run into problems like this, I’m amazed at the foresight of the software engineers that develop these packages.
Posted by Elliott Weix.