library(tidyverse)
pendulum <- read_csv("data/pendulum.csv", show_col_types = FALSE) |>
mutate(period_s = time_10_s / 10)8 Plotting with ggplot2
ggplot2 is the tidyverse’s plotting package. This chapter builds one figure from the pendulum data in stages, then shows a handful of variations you will need in a first-year lab.
The mutate() adds the period of a single swing, as in Chapter 7.
8.1 The grammar
Every ggplot2 figure is made of the same three parts. The data is a data frame. The aesthetic mappings, written inside aes(), say which column goes to which visual property: this column on the x axis, that one on the y axis, another as color. The geoms say what to draw: points, lines, error bars. You start with ggplot() and add the parts together with +.
ggplot(pendulum, aes(x = length_m, y = period_s)) +
geom_point()
There are 27 rows, but the three trials at each length nearly coincide, so you see what looks like nine points.
8.2 Means and error bars
Three nearly identical points per length are better shown as one mean with an error bar. That needs pendulum_summary from Chapter 7, here with only the mean period and its standard error:
pendulum_summary <- pendulum |>
summarise(
period_se = sd(period_s) / sqrt(n()),
period_s = mean(period_s),
.by = length_m
)
pendulum_summary
#> # A tibble: 9 × 3
#> length_m period_se period_s
#> <dbl> <dbl> <dbl>
#> 1 0.2 0.00120 0.897
#> 2 0.3 0.00418 1.10
#> 3 0.4 0.00328 1.27
#> 4 0.5 0.00173 1.42
#> 5 0.6 0.00186 1.55
#> 6 0.7 0.001000 1.68
#> 7 0.8 0.000882 1.79
#> 8 0.9 0.00203 1.90
#> 9 1 0.00203 2.00geom_errorbar() needs two extra aesthetics, ymin and ymax, for the bottom and top of each bar:
ggplot(pendulum_summary, aes(x = length_m, y = period_s)) +
geom_errorbar(
aes(ymin = period_s - period_se, ymax = period_s + period_se),
width = 0.03
) +
geom_point()
The error bars are there. They are just small: the standard errors are between 1 and 4 milliseconds on periods of one to two seconds, so each bar is shorter than the point drawn on top of it. All you can see is the horizontal caps. Timing ten swings and dividing by ten is a precise measurement, and the figure reports that. Do not inflate error bars to make them visible.
8.3 Adding the theory
The small-angle prediction is \(T = 2\pi\sqrt{L/g}\). Write it as the function from Chapter 4 and hand it to geom_function(), which evaluates it across the x range of the plot and draws a smooth curve. A plot can be stored in a variable like anything else, so the code below saves the finished figure as period_plot and then prints it.
pendulum_period <- function(length_m, g = 9.81) {
2 * pi * sqrt(length_m / g)
}
period_plot <- ggplot(pendulum_summary, aes(x = length_m, y = period_s)) +
geom_function(fun = pendulum_period, color = "gray50") +
geom_errorbar(
aes(ymin = period_s - period_se, ymax = period_s + period_se),
width = 0.03
) +
geom_point() +
labs(
x = "Length (m)",
y = "Period (s)",
title = "Period of a simple pendulum",
caption = "Points: mean of 3 trials. Curve: small-angle theory, g = 9.81 m/s²."
) +
theme_bw()
period_plot
Layers are drawn in the order you add them, so the curve goes first and the points sit on top of it. labs() sets the axis labels, title, and caption. length_m is a fine column name and a poor axis label. theme_bw() changes the overall look to a white panel with a border. Without a theme you get ggplot2’s default gray panel. The other figures in this book use the lighter theme_minimal(). Pick one and use it for the whole report.
8.4 Linearizing
A straight line is stronger evidence than a curve that looks right, because your eye is good at spotting departures from one. Squaring the theory gives \(T^2 = (4\pi^2/g)\,L\), so \(T^2\) plotted against \(L\) should be a straight line through the origin. You can do arithmetic inside aes():
ggplot(pendulum_summary, aes(x = length_m, y = period_s^2)) +
geom_smooth(method = "lm", se = FALSE, color = "gray50", linewidth = 0.5) +
geom_point() +
labs(x = "Length (m)", y = "Period squared (s²)")
geom_smooth(method = "lm") draws the best-fit straight line through the points, and se = FALSE turns off the shaded band it adds by default. It also prints a message naming the formula it used, y ~ x, which you can ignore. The slope of that line is \(4\pi^2/g\), which means this plot contains a measurement of \(g\). Getting the number out, with its uncertainty, is the subject of Chapter 9.
8.5 Color: mapping versus setting
So far color has been set: color = "gray50" sits outside aes() and applies one fixed color to the whole layer. Color can also be mapped to a column, by putting it inside aes(). Then ggplot2 chooses the colors and draws a legend.
ggplot(pendulum, aes(x = length_m, y = period_s, color = factor(trial))) +
geom_point() +
labs(x = "Length (m)", y = "Period (s)", color = "Trial")
trial is stored as the numbers 1, 2, 3, and ggplot2 would treat a number as a continuous quantity and give you a gradient. Wrapping it in factor() converts it to a factor, R’s type for a categorical variable, so the values become labels for three separate groups. The rule to remember: inside aes() goes a column name, outside goes a fixed value. Writing aes(color = "blue") is the classic slip. It produces red points and a legend that says “blue”, because ggplot2 took "blue" as data.
The same distinction holds for size, shape, alpha (transparency), and linewidth.
8.6 Log axes
The book’s second data set, cooling.csv, is the temperature of a cup of hot water, read every two minutes as it returns to room temperature, about 21.5 °C. Newton’s law of cooling says the temperature excess over the room decays exponentially, and an exponential is a straight line when the y axis is logarithmic.
cooling <- read_csv("data/cooling.csv", show_col_types = FALSE) |>
mutate(excess_c = temp_c - 21.5)
ggplot(cooling, aes(x = time_s, y = excess_c)) +
geom_point() +
scale_y_log10() +
labs(x = "Time (s)", y = "Temperature above room (°C)")
scale_y_log10() changes the axis, not the data: the labels still read in degrees. The points fall close to a straight line, with a little scatter at the end, where the excess is only a few degrees and a 0.1 °C step in the thermometer reading shows. There is a scale_x_log10() too, for power laws, which are straight when both axes are logarithmic.
8.7 Facets
facet_wrap() splits one plot into a panel per group, all sharing the same axes. Here is the pendulum data with one panel per trial:
ggplot(pendulum, aes(x = length_m, y = period_s)) +
geom_point(size = 1) +
facet_wrap(vars(trial)) +
labs(x = "Length (m)", y = "Period (s)")
The three panels are indistinguishable, which is the result: the trials are consistent. Facets are most useful when the groups differ, for example the same experiment run with three different masses.
geom_line(), which joins the rows with a line, is the other geom you will need. It turns up in Chapter 9 and Chapter 10.
8.8 Saving a figure
ggsave() writes a plot to a file. The file type comes from the extension.
ggsave("figures/pendulum-period.png", plot = period_plot,
width = 6, height = 4, dpi = 300)Width and height are in inches, and 300 dpi is the usual standard for print. The figures folder has to exist first. Save with code, not with the Export button in the Plots pane, so the figure comes out the same size every time you rerun the script.
The linearized plot produced a straight line and a promise that its slope is \(4\pi^2/g\). Chapter 9 keeps that promise: it fits the line, extracts the slope and its uncertainty, and turns them into a value for \(g\).