3  Categories: order, names, facets

When you split colours or figures by category (species, island, sex), what you care about is the order and the displayed names.

3.1 Giving categories display names and an order

R’s factor and pandas’ categorical type (Categorical) are both types that hold “the possible values and their order”. If you decide them once on the data side, the legend, axes and facets all get the same order and names.

NoteMissing sex

The 11 penguins of unknown sex are excluded. You could also keep them by creating an “Unknown” level. Write what was excluded in the figure’s caption.

3.2 Bar charts: counting vs plotting values as they are

ggplot2 distinguishes geom_bar(), which counts the data to make bars, from geom_col(), which uses the values as they are for the bar heights.

You can see that Biscoe Island has Gentoo and Adelie, Dream Island has Chinstrap and Adelie, and Torgersen Island has only Adelie. This imbalance between islands and species leads into Simpson’s paradox in Chapter 6.

3.3 Ordering by value

When categories have no natural order, ordering them by the size of a value makes them easier to read. We order the NHANES race/ethnicity categories by median BMI.

3.4 Facets: arranging small plots

Arranging plots of the same form side by side, one per category, is called faceting (small multiples). It can be easier to compare than distinguishing by colour.

3.4.1 Aligned axes or per-panel axes

By default, facets use the same axis ranges for all panels, so that values can be compared across panels. When you want different ranges per panel (when the magnitudes differ a lot), use scales = "free_y" in ggplot2 and facet_kws={"sharey": False} in seaborn.

WarningWith free axes, you can’t compare across panels

If axis ranges differ between panels, comparing visual heights and positions is meaningless. For facets comparing quantities in the same unit, keep the axes aligned.

ImportantChapter summary
  • Decide category names and order once, on the data side (R’s factor, pandas’ Categorical)
  • geom_bar() counts, geom_col() uses values as they are. Stacking and proportions via position =
  • Order categories without a natural order by the size of a value
  • Facets: facet_wrap / facet_grid; in seaborn, col= and row= of figure-level functions. Be aware of whether to align the axes