Describe a plot as data, aesthetics and geometries.
Build a plot one layer at a time in ggplot2 or plotnine.
Tell the difference between mapping a variable and setting a fixed value.
Add labels and a theme, and save a plot at a chosen size.
By the end of this chapter you will build this figure, layer by layer.
1.1 The grammar of graphics Core
Both ggplot2 (R) and plotnine (Python) are based on the grammar of graphics(Wickham 2010). Instead of choosing from a menu of chart types, you describe a plot in parts:
Part
Question it answers
Example
Data
Which data frame?
penguins
Aesthetics (aes)
Which variable goes on which visual property?
bill length on x, bill depth on y
Geometries (geom_)
What marks are drawn?
points, lines, bars
Scales
How are values turned into positions and colours?
log axis, a colour palette
Theme
How do the non-data parts look?
fonts, grid lines, background
You add these parts together with +. Change one part, and only that part of the plot changes. This makes it easy to try ideas quickly.
# A tibble: 6 × 8
species island bill_length_mm bill_depth_mm flipper_length_mm body_mass_g
<chr> <chr> <dbl> <dbl> <dbl> <dbl>
1 Adelie Torgersen 39.1 18.7 181 3750
2 Adelie Torgersen 39.5 17.4 186 3800
3 Adelie Torgersen 40.3 18 195 3250
4 Adelie Torgersen NA NA NA NA
5 Adelie Torgersen 36.7 19.3 193 3450
6 Adelie Torgersen 39.3 20.6 190 3650
# ℹ 2 more variables: sex <chr>, year <dbl>
import pandas as pdfrom plotnine import*penguins = pd.read_csv("data/penguins.csv")penguins.head()
species
island
bill_length_mm
bill_depth_mm
flipper_length_mm
body_mass_g
sex
year
0
Adelie
Torgersen
39.1
18.7
181.0
3750.0
male
2007
1
Adelie
Torgersen
39.5
17.4
186.0
3800.0
female
2007
2
Adelie
Torgersen
40.3
18.0
195.0
3250.0
female
2007
3
Adelie
Torgersen
NaN
NaN
NaN
NaN
NaN
2007
4
Adelie
Torgersen
36.7
19.3
193.0
3450.0
female
2007
Each row is one penguin. We have its species, the island it was found on, bill length and depth, flipper length, body mass, sex and the year it was measured.
1.3 Layer 1: data and aesthetics Core
Start by saying which data to use, and which variables map to x and y.
ggplot(penguins, aes(x = bill_length_mm, y = bill_depth_mm, colour = species)) +geom_point() +geom_smooth(method ="lm", se =FALSE)
p = (ggplot(penguins, aes(x="bill_length_mm", y="bill_depth_mm", color="species"))+ geom_point()+ geom_smooth(method="lm", se=False))p.show()
Within every species, longer bills are deeper. The overall negative trend was created by mixing three groups with different averages. This is known as Simpson’s paradox, and we found it simply by adding one aesthetic. It is a good example of why exploring your data matters: it can change your conclusion, not just your figure.
ImportantDesign principle: aesthetics are inherited
Anything inside ggplot(aes(...)) applies to every layer. That is why both the points and the trend lines were coloured by species, and why we got one trend line per species.
1.6 Mapping versus setting Core
This is the most common source of confusion for beginners.
Mapping links a visual property to a variable. It goes insideaes().
Setting gives a visual property one fixed value. It goes outsideaes().
p = (ggplot(penguins, aes(x="bill_length_mm", y="bill_depth_mm"))+ geom_point(color="steelblue", size=2, alpha=0.6))p.show()
Here every point is the same blue, at the same size, partly transparent. If you accidentally write aes(colour = "steelblue"), the software treats "steelblue" as a tiny dataset with one category, and you get a legend with a single entry and a default colour. Try it to see.
1.7 Layer 4: labels and theme Core
Readable labels and a cleaner theme make a big difference. Notice the title is a headline: it says what to notice.
ggplot(penguins, aes(x = bill_length_mm, y = bill_depth_mm, colour = species)) +geom_point(alpha =0.8) +geom_smooth(method ="lm", se =FALSE) +labs(title ="Within each species, longer bills are deeper",x ="Bill length (mm)",y ="Bill depth (mm)",colour ="Species") +theme_minimal(base_size =13)
p = (ggplot(penguins, aes(x="bill_length_mm", y="bill_depth_mm", color="species"))+ geom_point(alpha=0.8)+ geom_smooth(method="lm", se=False)+ labs(title="Within each species, longer bills are deeper", x="Bill length (mm)", y="Bill depth (mm)", color="Species")+ theme_minimal(base_size=13))p.show()
1.8 Saving a plot Core
Store the plot in an object, then save it with an explicit size. Set the size to how big the figure will be when it is used, not how big it looks on your screen. We cover this properly in Multi-panel figures and export.
ggplot(penguins, aes(x = flipper_length_mm, y = body_mass_g, colour = species)) +geom_point(size =2.5, alpha =0.7) +labs(title ="Gentoo penguins are the largest, with the longest flippers",x ="Flipper length (mm)", y ="Body mass (g)", colour ="Species") +theme_classic(base_size =13)
p = (ggplot(penguins, aes(x="flipper_length_mm", y="body_mass_g", color="species"))+ geom_point(size=2.5, alpha=0.7)+ labs(title="Gentoo penguins are the largest, with the longest flippers", x="Flipper length (mm)", y="Body mass (g)", color="Species")+ theme_classic(base_size=13))p.show()
Other headlines are possible, for example “Heavier penguins have longer flippers”. The point is to decide.
ExerciseShape as a second cue Extension
Level:
Map species to both colour and shape. Why might this help some readers? What happens to the legend?
ggplot(penguins, aes(x = flipper_length_mm, y = body_mass_g,colour = species, shape = species)) +geom_point(size =2.5, alpha =0.7) +labs(x ="Flipper length (mm)", y ="Body mass (g)",colour ="Species", shape ="Species")
p = (ggplot(penguins, aes(x="flipper_length_mm", y="body_mass_g", color="species", shape="species"))+ geom_point(size=2.5, alpha=0.7)+ labs(x="Flipper length (mm)", y="Body mass (g)", color="Species", shape="Species"))p.show()
Using shape as well as colour means the groups can still be told apart in greyscale and by readers with colour vision deficiency. Because both legends have the same title, they are merged into one. Give them different titles and you get two separate legends.
1.10 Summary
TipKey points
A plot is built from data, aesthetics, geometries, scales and a theme, added together with +.
Variables are mapped inside aes(); fixed values are set outside it.
Aesthetics in the main ggplot() call are inherited by every layer.
Adding one aesthetic can change what you conclude, so explore before you explain.
Save plots with an explicit width, height and resolution.
Wickham, Hadley. 2010. “A Layered Grammar of Graphics.”Journal of Computational and Graphical Statistics 19 (1): 3–28. https://doi.org/10.1198/jcgs.2009.07098.