1 Grammar of graphics: ggplot2 and matplotlib / seaborn
Code cells can be re-run by editing them and pressing “Run Code”. Switch between R and Python with the tabs on each example. The initial load takes 1–2 minutes.
First, let’s get a grip on the difference in philosophy between the two languages. Once you understand this, in later chapters you will know “what to change to get what you want”.
1.1 Data
For 344 penguins we have bill length (bill_length_mm), bill depth (bill_depth_mm), flipper length (flipper_length_mm), body mass (body_mass_g) and more.
1.2 ggplot2: building figures with a “grammar”
ggplot2 is built on the idea of a grammar of graphics. A figure is written as a combination of the following components.
| Component | Meaning | Example |
|---|---|---|
| Data | The data frame to plot | ggplot(penguins, ...) |
| Mapping (aes) | Maps variables to visual properties (x, y, colour, shape, size) | aes(x = bill_length_mm, colour = species) |
| Geometry (geom) | What to draw with (points, lines, bars, boxes) | geom_point(), geom_boxplot() |
| Statistic (stat) | How to summarise the data before drawing (counting, smoothing) | stat_smooth(), the counting in geom_histogram() |
| Scale | How variable values are converted to concrete colours and positions | scale_colour_manual(), scale_x_log10() |
| Coordinates (coord) | The coordinate system | coord_flip(), coord_cartesian() |
| Facets | Splitting into small plots | facet_wrap(~ island) |
| Theme | Appearance unrelated to the data (background, text) | theme_minimal() |
You chain these together with +.
If you want to colour by species, you just add one thing to the mapping. The legend is created automatically too.
The 2 penguins with missing flipper length / body mass are not drawn, and a warning is shown. This is important information telling you what dropped out of the figure (Chapter 9).
1.3 matplotlib: drawing by “commanding” a Figure and Axes
matplotlib’s style is to create axes (Axes) inside a figure (Figure) and command those axes to draw.
- Figure: the whole figure (the sheet of paper). Has a size and resolution
- Axes: the area of one graph (holds the axes, ticks and drawings). One Figure can hold any number of them
To colour by species, you need to split the data by species and draw each layer yourself. For the legend, too, you attach a label to each drawing and call it yourself.
plt.xxx() vs ax.xxx()
matplotlib has two styles: drawing on “the current axes” as in plt.plot() (the pyplot style), and drawing on specified axes as in ax.plot() (the object-oriented style). To avoid confusion when handling multiple panels or wrapping code in functions, this hands-on consistently uses the style that starts with fig, ax = plt.subplots() and draws with ax..
1.4 seaborn: drawing “from a data frame” on top of matplotlib
seaborn is a library built on top of matplotlib that handles colouring, legends and statistical summaries just by specifying column names of a data frame. It feels similar to ggplot2.
Even after drawing with seaborn, the returned ax is an ordinary matplotlib Axes, so you can fine-tune it with ax.set_xlabel(), ax.text() and so on. “Draw roughly with seaborn, then finish with matplotlib” is the basic workflow in Python.
1.4.1 seaborn’s two kinds of functions
| Kind | Examples | Returns | When to use |
|---|---|---|---|
| Axes-level | scatterplot, boxplot, histplot, regplot |
a matplotlib Axes |
Draw on axes you created (ax=). When assembling multiple panels yourself |
| Figure-level | relplot, catplot, displot, lmplot |
a FacetGrid (the whole figure) |
When you want facets (small plots side by side) created automatically |
Figure-level functions specify the figure size not with figsize but with the height of one panel, height, and its aspect ratio, aspect, and they do not accept ax=. This difference is easy to get confused by, so keep it in mind.
1.5 Comparing the same figure three ways
| ggplot2 | seaborn | matplotlib only | |
|---|---|---|---|
| Colour by group | aes(colour = column) |
hue="column" |
Loop over groups and draw |
| Shape by group | aes(shape = column) |
style="column" |
marker= per group |
| Legend | Automatic (merged into one if colour and shape use the same variable) | Automatic | label= and ax.legend() |
| Missing values | Dropped with a warning | Dropped silently | Dropped silently (NaN is not drawn) |
- ggplot2 assembles data, mapping, geoms, stats, scales, coordinates, facets and themes with
+ - matplotlib draws by commanding a Figure (paper) and Axes. Stick to
fig, ax = plt.subplots()andax. - seaborn draws from data frames on top of matplotlib. There are two kinds: axes-level (accepts
ax=) and figure-level (creates facets) - Draw with seaborn, then finish with matplotlib’s
ax