9 Into the Tidyverse: Graphs with ggplot2
By the end of this chapter you should be able to:
- Explain the grammar of graphics: data, aesthetic mappings, and geoms.
- Build scatterplots, bar charts, and boxplots with
ggplot(). - Tell setting an aesthetic from mapping one.
- Split a plot into small multiples with
facet_wrap()andfacet_grid(). - Add labels and your own colors, and save a plot with
ggsave().
In the last three chapters you used dplyr to filter, sort, and summarize the nycflights13 data. Tables of numbers answer precise questions, but they are a poor way to see a pattern. Do flights that leave late also arrive late? Which airline flies the longest routes? Is there a weekly rhythm to the number of flights? A graph answers each of these at a glance.
This chapter introduces ggplot2, the tidyverse package for graphs. Everything in it builds on one short template, and the same ideas carry straight over to the maps in the next chapter.
Predict what happens, then run it.
Yes, it runs. -> is the assignment arrow pointing the other way: it stores flights in a new object called flights.new. It is legal R, but uncommon. The tidyverse style guide recommends <-, so that the name of the object you are making is always on the left, where readers look for it.
glimpse() prints one line per column, with its type (<int>, <dbl>, <chr>) and the first few values. It is a quick check, before you plot anything, that the data loaded and that the columns have the types you expect.
9.1 The grammar of graphics
9.1.1 ggplot2 expects tidy data
ggplot2 is built for tidy data, the same shape dplyr produces: each variable is a column, each observation is a row, and each value is a cell. Every variable you want on an axis, or as a color, or to split a plot by, must be its own column. flights is already tidy: one row per flight and one column per thing recorded about it. If a variable is spread over several columns (say, one column per year), you would reshape it first with pivot_longer() from tidyr.
9.1.2 What is ggplot2?
ggplot2 is part of the tidyverse, so library(tidyverse) loads it. The package is called ggplot2, but its main function is ggplot(). It was written by Hadley Wickham, based on Leland Wilkinson’s book The Grammar of Graphics, and it has three things going for it:
- A readable graph takes very little code, because the defaults are good.
- You can still change every part of the graph when you need to.
- Graphs are built in layers, joined with
+, so you can start simple and add one piece at a time.
9.1.3 Every graph has the same parts
The grammar of graphics is the idea that any chart, from a scatterplot to a map, can be described with the same small set of parts (Table 9.1).
| Part | What it is | In ggplot2 |
|---|---|---|
| Data | The tidy table you plot | ggplot(data = flights) |
| Aesthetics | Visual properties, such as x position, y position, color, or size, that a column is shown with | aes(x = dep_delay, y = arr_delay) |
| Geoms | The marks that show the data: points, bars, lines, boxes | geom_point(), geom_bar() |
| Scales | How data values turn into visual values: which colors, which axis breaks | scale_fill_manual(), scale_x_log10() |
| Facets | Splitting the data into small plots, one per group | facet_wrap() |
| Coordinates | Where the marks land on the page | coord_flip(), or a map projection |
The key word is aesthetic: a visual property of a mark. aes() is where you connect the columns in your data to those properties. A bar chart and a scatterplot can share the same data and the same coordinates; only the geom changes.
9.1.4 Choosing a geom
ggplot2 has more than 40 geoms. To pick one, first ask what kinds of variables you are plotting (Table 9.2). The answer narrows it down to two or three choices.
| You are plotting | Try |
|---|---|
| One continuous variable | geom_histogram(), geom_density() |
| One categorical variable | geom_bar() |
| Two continuous variables | geom_point(), geom_smooth() |
| A categorical x and a continuous y | geom_boxplot(), geom_col() |
| Change over time | geom_line() |
Posit’s ggplot2 cheatsheet groups all the geoms this way. In RStudio, find it under Help > Cheat Sheets.
9.1.5 The template
Every ggplot follows the same template:
ggplot(data = <DATA>) +
<GEOM_FUNCTION>(mapping = aes(<MAPPINGS>))Swap in a data frame, a geom function, and the mappings, and you have a plot. Building one takes five steps, but only the first three are required:
- Start with tidy data:
ggplot(data = flights). - Map variables to aesthetics:
aes(x = dep_delay, y = arr_delay). - Add a geom to draw them:
+ geom_point(). - Adjust the scales and coordinates, for example
+ scale_x_log10(). - Add labels:
+ labs(title = "...").
Two rules trip people up. First, the + must go at the end of a line, not the start of the next one; otherwise R thinks the command has ended. Second, ggplot2 uses + to add layers, while dplyr uses |> to pass data along. You can pipe data into ggplot(), but after that, every layer is joined with +.
The argument names data = and mapping = are optional, so ggplot(flights) + geom_point(aes(x = dep_delay, y = arr_delay)) works too. Most code you find online leaves them out.
9.2 Scatterplots and aesthetics
9.2.1 A first scatterplot
Do flights that leave late arrive late? To keep the plot readable, start with the October flights, and drop the cancelled ones, which have no delay values:
Each point is one October flight. The points form a rising band: flights that leave late arrive late, by about the same amount. Without drop_na(), the plot would look the same, but ggplot2 would warn that it had removed rows with missing values.
What does a point far above the band mean? A flight that arrived much later than its departure delay predicts, perhaps because it was held in the air or waited a long time on the runway.
9.2.2 Adding a trend line
geom_smooth() draws a trend line. Layer it on top of the points with another +:
Two things changed. The mapping moved into ggplot(). Mappings set there apply to every layer, so geom_point() and geom_smooth() both use the same x and y, and you don’t have to repeat them. And the layers draw in order, so the line sits on top of the points.
By default, geom_smooth() fits a smooth curve, with a gray band showing its 95% confidence interval. R prints a message saying which method it used. For a straight regression line, use geom_smooth(method = "lm"), and to hide the band, add se = FALSE.
9.2.3 Setting an aesthetic
To make the points blue and the line red, give each geom a color outside aes():
This is setting an aesthetic: every mark gets the same fixed value, whatever the data say. It is a design choice, not a data choice. Each geom takes its own settings, so here the points are blue, and the line is red and thicker (linewidth = 2).
Note the quotes around "blue" and "red". R knows 657 color names (run colors() to see them all), and it also takes hex codes such as "#2C5080".
9.2.4 Mapping an aesthetic
Now give each origin airport its own color. Move color inside aes(), and give it a column instead of a color:
This is mapping an aesthetic: the color now comes from the data. ggplot2 picks one color for each value of origin, and builds the legend for you. Because color is mapped in ggplot(), geom_smooth() also splits by airport, and draws three trend lines.
Table 9.3 sums up the difference. It is the most important idea in this chapter.
| Setting | Mapping | |
|---|---|---|
| Where | In the geom, outside aes() |
Inside aes() |
| Value | A fixed value: color = "blue" |
A column: color = origin |
| Result | Every mark looks the same | Marks differ by the data, with a legend |
What happens if you write aes(color = "blue")? Inside aes(), ggplot2 treats "blue" as a data value, as if every row had a column whose value was the word “blue”. It makes a one-item legend called blue, and colors the points with its first default color, which is a salmon pink. Try it in the box above. If your points come out the wrong color with a strange legend, check whether a setting has slipped inside aes().
Move color = origin out of ggplot(aes()) and into geom_point(aes()) instead. Before you run it, predict: how many trend lines will you get now? Why?
9.2.5 Too many colors
Try mapping color to the airline, carrier. With all 16 airlines, the colors become hard to tell apart, so this code keeps six large ones first:
The data flow into ggplot() through the pipe, and from there on the layers are joined with +. Even with six carriers, the points pile on top of each other. Color works best for about five groups or fewer. Facets, later in this chapter, are a better fix.
9.3 Bar charts and boxplots
9.3.1 Counting with geom_bar()
How many October flights did each airline fly? A bar chart compares counts across categories:
You only map x. geom_bar() counts the rows for each carrier itself, the same as count(carrier) would, and plots the counts as the bar heights. If you already have a table of counts, for example from group_by() and summarize(), use geom_col(aes(x = carrier, y = n)) instead, which draws the heights you give it.
United (UA), ExpressJet (EV), and JetBlue (B6) flew the most, with about 5,000 flights each. Hawaiian (HA) flew just 21. The carrier codes are hard to read; the airlines table in nycflights13 has the full names, which you could join in.
9.3.2 fill and color
For bars, boxes, and polygons, fill colors the inside, and color only the outline. (For points and lines, color is the one to use.) Map fill to the carrier:
Each bar now has its own color and a legend entry. But the legend only repeats the x axis, so it adds nothing. Hide it with show.legend = FALSE inside geom_bar(). Color earns its place when it shows a different variable from x.
9.3.3 Stacked bars
Map fill to a different variable from x. Here x is the day of the month, and the colors show which of five carriers flew that day:
Each bar splits into colored segments, one per carrier, and the bar’s height is still the total number of flights that day. This is a stacked bar chart. The regular dips are Saturdays, when airlines schedule fewer flights.
Stacking makes the totals easy to read, but the middle segments are hard to compare, because they don’t sit on a shared baseline. The position argument gives two alternatives:
position = "fill" stretches every bar to the same height, so you compare proportions. The y axis would still say “count”, although it now shows a share, which is why the code relabels it with labs(). position = "dodge" puts each day’s bars next to each other on a shared baseline, so you can compare counts directly. With 31 days and five carriers it gets crowded; dodging works best with only a few categories on x.
9.3.4 Boxplots
Which airlines fly the longest routes? A boxplot compares a continuous variable across categories. Map a categorical x and a continuous y:
A boxplot summarizes each group in five numbers. The box runs from the 25th to the 75th percentile, so it holds the middle half of the flights. The thick line is the median. The whiskers reach the furthest points within 1.5 times the height of the box, and anything beyond them is drawn as a dot: an outlier.
United (UA) flies the longest routes, with a median of about 1,400 miles, and its outliers near 5,000 miles are its flights from Newark to Honolulu. Southwest (WN) flies the shortest, with a median of about 750 miles. A boxplot hides the shape of the data inside the box; geom_violin() is an alternative that shows it.
9.4 Small multiples with facets
9.4.1 facet_wrap()
Sixteen colors on one chart are impossible to tell apart. A better idea is small multiples: one small chart per group, all with the same axes. In ggplot2 this is called faceting:
facet_wrap(~ carrier) draws one panel per carrier. The tilde, ~, makes a formula: read ~ carrier as “split by carrier”. The panels share their axes, so you can compare them directly. nrow or ncol sets the shape of the grid, as in facet_wrap(~ carrier, ncol = 4).
alpha = 0.3 makes each point 70% transparent, so places where many points overlap look darker, and you can see where most flights fall. Look at the panel for HA (Hawaiian Airlines): it is nearly empty, because Hawaiian flew only one flight a day from New York. You would never have spotted that in a single chart with 16 colors.
9.4.2 facet_grid()
To split by two categorical variables, use facet_grid(rows ~ columns):
flights |>
ggplot(aes(x = distance, y = air_time)) +
geom_point(alpha = 0.3) +
facet_grid(origin ~ month)This makes 3 rows (one per airport) by 12 columns (one per month): 36 panels. Read across a row to follow one airport through the year, or down a column to compare the airports in one month. At this size the axis labels overlap; fixes include filtering to a few months, or setting fewer breaks with scale_x_continuous(breaks = c(0, 1000)). facet_grid(~ month) makes columns only.
Use facet_wrap() for one variable with many levels, and facet_grid() when you want to cross two variables.
9.5 Finishing a plot
9.5.1 Choosing your own colors
Every mapped aesthetic has a scale, which controls how data values turn into visual values. To pick the colors yourself, replace the default fill scale with scale_fill_manual():
Naming each value ("EWR" = ...) guarantees each airport keeps its color, even if the order of the data changes. Match the scale to the aesthetic: scale_fill_manual() for fills, scale_color_manual() for points and lines.
The six-character codes are hex codes: two characters each for the red, green, and blue in the color. Choosing colors that work for everyone is harder than it looks. About one man in twelve has some form of color blindness. Websites such as https://colorbrewer2.org suggest sets of colors that work for color-blind readers and in grayscale, and scale_fill_viridis_d() uses the viridis palette, which is designed for both.
9.5.2 Adding labels with labs()
A column name such as dep_delay means something to you, but not to your reader. labs() sets every label in one call:
The argument names match the aesthetics: x, y, color, fill. Here color = "Origin airport" renames the legend, because color is the mapped aesthetic. A good habit for every plot you hand in: a title, axis labels with units, and the data source in the caption.
9.5.3 Themes
A theme controls everything that isn’t data: the background, the grid lines, the fonts. Add one as another layer. theme_minimal() removes the gray background, and theme_bw() and theme_classic() are worth trying too:
9.5.4 Saving a plot with ggsave()
You could export a plot from RStudio’s Plots pane, but then it comes out at whatever size the pane happens to be. ggsave() makes the size and resolution part of your code, so the figure is the same every time you knit:
# Create your plot
ggplot(data = october_flights) +
geom_point(mapping = aes(x = dep_delay, y = arr_delay, color = origin)) +
theme_minimal()
# Save it as a high-resolution PNG file
ggsave(filename = "nyc_flights_delays_october.png",
width = 8,
height = 6,
dpi = 300) # good for print or presentationsggsave() saves the last plot you made. width and height are in inches, and dpi is the resolution in dots per inch: 300 is print quality. The file extension sets the type: .png, .pdf, .svg, or .jpg. The file goes into your working directory, which for an R Markdown file is the folder the .Rmd file is in. To save a plot that isn’t the last one, store it first, p <- ggplot(...), and then ggsave("file.png", plot = p).
9.6 Practice: June flights
These steps follow the in-class exercise.
Step 1: set up. Start a new R Markdown file, load the packages, and look at the data:
library(nycflights13)
library(tidyverse)
glimpse(flights)
flights |>
distinct(carrier)Step 2: plot. Graph air_time against distance for the June flights. Add a trend line, color the points by origin airport, and label the axes with units. Try it first:
flights |>
filter(month == 6) |>
ggplot(aes(x = distance, y = air_time)) +
geom_point(aes(color = origin), alpha = 0.3) +
geom_smooth() +
labs(x = "Distance (miles)", y = "Air time (minutes)",
color = "Origin airport",
title = "Air time against distance, June 2013")The points fall close to a straight line, because air time grows with distance at roughly cruising speed. Points far off the line are worth asking about. Here color is mapped in geom_point() only, so there is a single trend line for all three airports.
Step 3: challenge. Which plane (tailnum) has the worst on-time record? This is a dplyr question, not a plotting one: you answered a version of it at the end of the last chapter. Once you have a table of planes with their share of late flights, try plotting it: a histogram of share_late shows whether a few planes are unusually bad, or whether lateness is spread across the whole fleet.
9.7 Check your understanding
In ggplot2, which function connects columns in your data to visual properties such as x, y, and color?
geom_point(color = "blue")is an example of:Writing
aes(color = "blue")makes all the points blue.Which geom counts the rows in each category for you?
For a bar chart, which aesthetic colors the inside of each bar?
Which bar position stretches every bar to the same height, so you can compare shares?
In a boxplot, the thick line across the box shows the:
facet_wrap(~ carrier)draws one panel for each carrier, with shared axes.In a chain of ggplot2 layers, the
+goes at the start of each new line.
Inside aes(), "blue" is treated as a data value, not a color. ggplot2 makes a legend entry called blue and uses its default color, a salmon pink. To make the points blue, set the color outside aes(): geom_point(color = "blue").
9.8 Summary
- ggplot2 builds graphs from the grammar of graphics: data, aesthetics that map columns to visual properties, and geoms that draw the marks, joined in layers with
+. - The template is
ggplot(data) + geom_function(aes(mappings)). Mappings inggplot()apply to every layer. - Choose the geom from the kinds of variables:
geom_point()andgeom_smooth()for two continuous variables,geom_bar()for counts of a category,geom_boxplot()for a continuous variable across categories. - Setting an aesthetic (outside
aes()) gives every mark the same value. Mapping one (insideaes()) ties it to a column and makes a legend. - For bars,
fillis the inside andcolorthe outline.position = "fill"compares shares;position = "dodge"compares counts. - Facets (
facet_wrap(),facet_grid()) make small multiples, a better choice than many colors. - Finish every plot with readable colors (
scale_fill_manual()), labels (labs()), and a theme, and save it withggsave().
9.9 Exercises
Use the flights data from nycflights13 for these exercises.
Histogram. Make a histogram of
distancewithgeom_histogram(). Changebinwidthto 100, then 500. What do you notice about the distances flown from New York?Sorted bars. Make a bar chart of the number of flights from each origin airport. Then make one for the 10 most common destinations (
dest). (Hint:count(),slice_max(), andgeom_col().)Delays by month. Use
group_by()andsummarize()to find the mean departure delay for each month, then plot it withgeom_line()andgeom_point(). Which months were worst?Set or map? Make a scatterplot of
distanceagainstair_timefor the January flights. First set every point to dark green. Then map color toorigin. Then mapsizetodep_delay. Which of these makes a useful plot?Facets. Make boxplots of
dep_delayfor eachorigin, then facet them bymonth. Usecoord_cartesian(ylim = c(-20, 100))to zoom in. What does zooming in show you that the full plot doesn’t?Finish and save. Take your favorite plot from these exercises, give it a title, axis labels with units, and a caption, apply
theme_minimal(), and save it as a PNG file 7 inches wide and 5 inches tall.Fix the code. Each chunk below has one mistake. Find and fix it.
ggplot(flights) + geom_point(aes(x = dep_delay, y = arr_delay), color = "origin") ggplot(flights, aes(x = carrier)) + geom_bar() flights |> ggplot(aes(x = carrier)) |> geom_bar()
9.10 Further reading
- R for Data Science (2nd ed.) (Wickham et al. 2023), free at https://r4ds.hadley.nz. The “Data visualization” chapter introduces ggplot2 with a different data set, and the “Layers” chapter goes further into geoms, facets, and positions.
- The ggplot2 website, https://ggplot2.tidyverse.org, has the reference page for every function in this chapter.
- Posit’s Data visualization with ggplot2 cheatsheet, https://posit.co/resources/cheatsheets/, lists the geoms by the kinds of variables they plot.
- ggplot2: Elegant Graphics for Data Analysis (3rd ed.), by Hadley Wickham, Danielle Navarro, and Thomas Lin Pedersen, free at https://ggplot2-book.org, explains the grammar of graphics in depth.
aes() connects columns to
aesthetics.
Tying an aesthetic to a column, inside aes(), as in
aes(color = origin). The look of each mark then comes from
the data, and ggplot2 adds a legend.
Short for geometric object: the marks a ggplot draws to show the data,
such as points (geom_point()), bars
(geom_bar()), or boxes (geom_boxplot()).
A plot of two continuous variables against each other, with one point
per observation. In ggplot2, geom_point().
A chart that compares counts or amounts across categories with bars.
geom_bar() counts rows for you; geom_col()
draws heights you give it.
A chart that summarizes a distribution: the box spans the middle half of
the values, a line marks the median, and dots beyond the whiskers are
outliers.
Giving every mark the same fixed value, outside aes(), as
in geom_point(color = "blue"). It is a design choice, not a
data choice.
A set of small charts, one per group, that share the same axes so they
can be compared directly. ggplot2 calls this faceting.
The tidyverse package for transforming data frames: filtering rows,
choosing columns, adding new columns, joining tables, and summarizing.
An R package of data on every flight that left New York City’s three
airports in 2013, including the flights data frame.
The tidyverse package for making plots and maps by adding layers.
A family of R packages (including dplyr,
ggplot2, and readr) for reading,
cleaning, reshaping, summarizing, and plotting data, all designed to
work together.
A bundle of code, written by other users, that adds new functions to R.
Install it once with install.packages(), then load it in
each session with library().
Data arranged so that each variable is a column, each observation is a
row, and each value has its own cell.
In R, a named piece of memory that holds data, such as
months <- 12. In a dataset, a measured characteristic,
such as median income; each Census variable has a code.
One thing that was measured or recorded, such as a student, a county, or
a flight. In a data frame, each row is an observation.
Code that takes inputs (arguments), does a job, and returns an output,
such as mean(temps).
One piece of a plot or map, added with + and drawn on top
of the layers before it. In GIS, a layer holds one theme of features,
such as roads or soils.
The rules that turn data values into visual values: which colors, which
classes, which axis breaks. Every mapped aesthetic has one, and
functions such as scale_fill_manual() or
tm_scale_intervals() change it.
A method for flattening the curved graticule onto a flat map. Every
projection distorts shape, area, distance, or direction.
A one-page summary of a package or tool. Posit publishes them for dplyr,
ggplot2, RStudio, and more.
The integrated development environment (IDE) where you write and run R.
R does the computing; RStudio is the workspace around it.
R’s table: rows are observations and columns are variables. A tibble is
the tidyverse’s version of a data frame.
The operator |>, which passes the result on its left as
the first argument of the function on its right. Read it as “and then.”
An input to a function, written inside its parentheses.
A value that is unknown, written NA (“not available”) in R.
Most calculations with NA give NA; test for it
with is.na().
A range that is likely to contain the true value of something estimated
from data. geom_smooth() shades a 95% confidence interval
around its trend line.
A statistical model of how one variable (such as home price) changes
with one or more others (such as distance to downtown).
A six-character code for a color, such as #3182bd: two
characters each for its red, green, and blue.
The key that explains what the colors, sizes, or shapes on a plot or map
mean. ggplot2 and tmap build one for every mapped aesthetic.
Combining two tables by matching rows on a shared key column, such as
attaching Census data to boundaries by GEOID with
left_join().
A closed shape that represents an area, such as a county, a lake, or a
census tract.
A bar chart where each bar is split into colored segments, one per
group, so the bar’s height is the total.
The value below which a given share of the values fall: a quarter of
values are below the 25th percentile. quantile() in R.
The middle value when values are sorted, so half are above and half
below. Unlike counts, medians can’t be added across areas.
A value far from all the others. It may be real or an error, so check it
before you report it.
The settings for everything on a plot that isn’t data: background, grid
lines, fonts. Add one with a layer such as theme_minimal().
To build an R Markdown file into a finished document (HTML, PDF, or
Word). Knitting reruns every code chunk from the top in a fresh R
session.
Dots per inch: the resolution of a saved image. 300 dpi is print
quality.
A document format (.Rmd) that mixes formatted text with
chunks of R code. Knitting it runs the code and builds a finished
report.
A chart that divides a variable’s range into bins and draws a bar for
how many values fall in each. geom_histogram() in ggplot2.
A block of R code inside an R Markdown file, starting with
```{r} and ending with three backticks.