Skip to main content

16  Figures worth publishing

16.1 Introduction

A good physics figure makes one point at a glance, survives being printed in greyscale at the width of a journal column, and can be remade from the data at any time. ggplot2 is built for that. It implements the grammar of graphics, Leland Wilkinson’s idea that every chart is assembled from the same parts (Wilkinson 2005), in the layered form Hadley Wickham described (Wickham 2010): data, a mapping from variables to aesthetics such as position and colour, geometric objects that draw the data, scales that translate values into what you see, a coordinate system, facets, and a theme. Learn the parts once and you can build any figure, including ones no plotting library anticipated.

R for Data Science teaches the grammar in its chapters on visualization, layers and communication (Wickham et al. 2023), and the ggplot2 book covers every corner (Wickham 2016; Wickham et al., n.d.). This chapter assumes you have met the basics in earlier chapters and concentrates on what physics figures need: a clean theme, logarithmic scales, perceptually uniform colour, annotation, custom projections and saving at the right size. It works through the book’s data sets one figure at a time, with an orbitr simulation of the inner planets among them.

ggplot2 is also a good example of a tool that lasts. Its interface has grown for many years while keeping old code running, and when it does change something, such as the switch from size to linewidth for lines in version 3.4.0, it deprecates the old way gradually and with warnings, rather than breaking it overnight.

Prerequisites

library(tidyverse)

16.2 A theme for physics

ggplot2’s default theme, grey background and all, is designed for screens. Physics journals favour a plain look: a box around the panel, no grid lines, and tick marks pointing inward. A theme is a list of such choices, and a function that returns one can be reused across every figure in a paper, which is how figures in a long project stay consistent. Every figure in this book has used this one:

theme_physics <- function(base_size = 11, base_family = "") {
  theme_bw(base_size = base_size, base_family = base_family) +
    theme(
      panel.grid = element_blank(),
      axis.ticks.length = unit(-0.15, "cm"),
      axis.text.x = element_text(margin = margin(t = 6)),
      axis.text.y = element_text(margin = margin(r = 6)),
      strip.background = element_blank(),
      strip.text = element_text(face = "bold"),
      legend.key = element_blank()
    )
}

theme_set(theme_physics())

theme_set() makes it the default for every plot that follows. A negative tick length points the ticks inward, and the text margins move the labels clear of them. When one figure needs something different, add a theme() call to that figure alone; the default stays as it is.

16.3 The Hertzsprung–Russell diagram

Around 1911 Ejnar Hertzsprung, and in 1913 Henry Norris Russell, independently plotted stars’ luminosities against their colours and found that most fall on a single band, the main sequence, with giants above it and, as later surveys showed, white dwarfs below. With a parallax for each star, the diagram is two mutate()s away. A parallax ϖ in milliarcseconds puts a star at 1000/ϖ parsecs, so its absolute magnitude, the apparent magnitude it would have at 10 parsecs, is M = G + 5 log10(ϖ) − 10. Keeping only parallaxes measured to better than 10% keeps the distances honest:

stars <- read_csv("data/stars.csv.gz")

hr <- stars |>
  filter(parallax_mas / parallax_error_mas > 10) |>
  mutate(abs_mag_g = g_mag + 5 * log10(parallax_mas) - 10)

84,732 stars is too many for individual points, which pile up into a black smudge where the density is highest. Counting them in small two-dimensional bins with geom_bin_2d(), and colouring the bins on a logarithmic scale, shows the dense main sequence and the sparse white dwarfs in one picture. The viridis colour scales are designed to be perceptually uniform, so equal steps in the data look like equal steps in colour, and they stay readable in greyscale and for most colour-blind readers. Astronomers plot bright stars at the top, so the magnitude axis is reversed:

hr_plot <- ggplot(hr, aes(x = bp_rp, y = abs_mag_g)) +
  geom_bin_2d(binwidth = c(0.02, 0.08)) +
  scale_fill_viridis_c(option = "magma", transform = "log10", name = "Stars per bin") +
  scale_y_reverse() +
  annotate("text", x = 3.0, y = 8.4, label = "main sequence", angle = -33, size = 3.5) +
  annotate("text", x = 2.15, y = 0.4, label = "giants", size = 3.5, hjust = 0) +
  annotate("text", x = 1.02, y = 0.45, label = "red clump", size = 3.5, hjust = 1) +
  annotate("text", x = 0.55, y = 11.6, label = "white dwarfs", size = 3.5, hjust = 0) +
  labs(x = expression(italic(G)[BP] - italic(G)[RP]), y = expression("Absolute magnitude " * italic(M)[G]))

hr_plot
A two-dimensional histogram of absolute G magnitude against BP minus RP colour, with brighter stars at the top. A dense diagonal band, the main sequence, runs from blue and bright at upper left to red and faint at lower right, with a fainter parallel band just above it. A clump and a sparse branch of giants sit above, and a thin sequence of white dwarfs lies at lower left. Colours run from dark purple for few stars to yellow for many.
Figure 16.1: A Hertzsprung–Russell diagram of the simulated stars within 300 parsecs.

Several things the eye picks out are physics. The main sequence is a sequence of mass: stars burning hydrogen in their cores, hot and blue at the top, cool and red at the bottom. The fainter band just above it, about 0.75 magnitudes brighter, is unresolved binaries: two similar stars in one image look twice as bright, and −2.5 log10 2 ≈ −0.75. The clump is helium-burning giants, and the white dwarfs are the exposed cores of dead stars.

The labels use plotmath, R’s notation for mathematics in figures: italic(G)[BP] is an italic G with a subscript BP. ?plotmath lists everything it can do.

Finding the cluster

Somewhere in the catalog is an open cluster: stars born together, at one distance, with one age. They share a position on the sky and a parallax. A box in position and parallax pulls them out:

cluster <- hr |>
  filter(
    between(ra_deg, 123, 134),
    between(dec_deg, -41, -32),
    between(parallax_mas, 10.3, 11.5)
  )

nrow(cluster)
#> [1] 555

Overlaid on the field, the cluster draws a single clean main sequence, because all its stars share one distance and one age:

ggplot(hr, aes(x = bp_rp, y = abs_mag_g)) +
  geom_bin_2d(binwidth = c(0.02, 0.08), fill = "grey80") +
  geom_point(data = cluster, colour = "#1d3557", size = 0.9) +
  scale_y_reverse() +
  labs(x = expression(italic(G)[BP] - italic(G)[RP]), y = expression("Absolute magnitude " * italic(M)[G]))
The Hertzsprung–Russell diagram in grey, with a few hundred points overlaid in dark blue that trace a narrow main sequence from colour 0.2 to about 3, plus a parallel binary sequence just above it.
Figure 16.2: The open cluster (points) traces a single, narrow main sequence across the field stars (grey).

16.4 The sky

Positions on the sky live on a sphere, and showing a sphere on a flat page needs a projection. Packages exist for map projections, but for an all-sky plot the Hammer projection, which preserves area, is two formulas, and mutate() applies them. Astronomers draw right ascension increasing to the left, as it appears looking up, so the longitude is reversed:

hammer <- function(lon_rad, lat_rad) {
  denom <- sqrt(1 + cos(lat_rad) * cos(lon_rad / 2))
  tibble(
    x = 2 * sqrt(2) * cos(lat_rad) * sin(lon_rad / 2) / denom,
    y = sqrt(2) * sin(lat_rad) / denom
  )
}

sky <- stars |>
  mutate(
    lon = -(ra_deg - 180) * pi / 180,
    lat = dec_deg * pi / 180,
    hammer(lon, lat)
  )

A mutate() whose expression returns a tibble adds all of its columns at once, here x and y. A grid of lines of constant right ascension and declination, the graticule, is built the same way, as a tidy table of points grouped into lines:

graticule <- bind_rows(
  expand_grid(ra_deg = seq(0, 360, by = 60), dec_deg = seq(-90, 90, by = 2)) |>
    mutate(line = paste("ra", ra_deg)),
  expand_grid(dec_deg = seq(-60, 60, by = 30), ra_deg = seq(0, 360, by = 2)) |>
    mutate(line = paste("dec", dec_deg))
) |>
  mutate(hammer(-(ra_deg - 180) * pi / 180, dec_deg * pi / 180))

The cluster members found above get the same treatment, so they can be drawn on top in another colour:

cluster_sky <- cluster |>
  mutate(hammer(-(ra_deg - 180) * pi / 180, dec_deg * pi / 180))
ggplot(sky, aes(x, y)) +
  geom_point(shape = ".", alpha = 0.3, colour = "grey25") +
  geom_path(aes(group = line), data = graticule, colour = "#4a90c2", linewidth = 0.3) +
  geom_point(data = cluster_sky, colour = "#e76f51", size = 0.4) +
  coord_equal() +
  theme_void()
An elliptical map of the whole sky with a light blue grid of curved lines. Stars cover it evenly as fine grey speckle, except for a small dense knot drawn in orange right of centre and below the equator, the open cluster.
Figure 16.3: All 85,000 stars in a Hammer equal-area projection of the sky, with lines every 60° of right ascension and 30° of declination. The open cluster (orange) is a dense knot.

The stars spread evenly, as stars within a few hundred parsecs should, and the cluster appears as a knot of a few hundred stars. shape = "." draws each star as a single pixel, the right mark for tens of thousands of points. And note theme_void(): a sky map has no meaningful axes, so they go.

16.5 Orbits

My orbitr package (Rosenman 2026) returns its simulations as tidy tables, so its output takes every tool in this book. orbitr’s own plot_orbits() draws a quick picture; for a figure of your own design, the table goes straight into ggplot2. Here are the inner planets for two years, with a six-hour step, which the analysis in Chapter 13 shows is ample for a picture. shift_reference_frame() makes every position relative to the Sun:

library(orbitr)

inner <- load_solar_system(moon = FALSE, pluto = FALSE) |>
  simulate_system(time_step = 6 * seconds_per_hour, duration = 2 * seconds_per_year) |>
  shift_reference_frame(center_id = "Sun") |>
  filter(id %in% c("Mercury", "Venus", "Earth", "Mars")) |>
  mutate(
    id = factor(id, levels = c("Mercury", "Venus", "Earth", "Mars")),
    x_au = x / distance_earth_sun,
    y_au = y / distance_earth_sun
  )

final_positions <- inner |>
  filter(time == max(time))

A night-sky background suits the subject. The colours are chosen to be distinct from one another and to evoke each planet, and the labels sit beside each planet’s position at the end of the run:

planet_colours <- c(Mercury = "#b8b8b8", Venus = "#e9c46a", Earth = "#4ea8de", Mars = "#e76f51")

ggplot(inner, aes(x_au, y_au, colour = id)) +
  annotate("point", x = 0, y = 0, colour = "#ffd166", size = 9, alpha = 0.25) +
  annotate("point", x = 0, y = 0, colour = "#ffd166", size = 4) +
  geom_path(linewidth = 0.5, alpha = 0.85) +
  geom_point(data = final_positions, size = 2.6) +
  geom_text(
    data = final_positions,
    aes(label = id),
    nudge_x = 0.13, hjust = 0, size = 3.6, colour = "grey85"
  ) +
  scale_colour_manual(values = planet_colours, guide = "none") +
  coord_equal(xlim = c(-1.75, 1.75), ylim = c(-1.75, 1.75)) +
  theme_void() +
  theme(plot.background = element_rect(fill = "#0b1026", colour = NA))
Four nested elliptical orbits around a glowing yellow Sun on a dark blue background: grey Mercury, gold Venus, blue Earth and orange Mars, each with a dot and a label at its final position. Mercury's orbit is slightly off-centre; the others are nearly circular.
Figure 16.4: The inner solar system for two years, simulated with orbitr and drawn with ggplot2. Points mark each planet’s position at the end of the run.

Two light points, one large and faint, one small and bright, make the Sun glow. Mercury’s orbit sits slightly off-centre, the mark of its eccentricity of 0.21, the largest of any planet; the others look like circles to the eye, as they should, since Earth’s eccentricity is under 0.02. Everything else is the grammar from the start of the chapter: a path layer for the orbits, a point layer and a text layer for the final positions, a manual colour scale, an equal-aspect coordinate system and a theme.

16.6 A sudden impulse

The magnetometer’s sudden impulse, seen in Chapter 2 at one-minute resolution, deserves a closer look at full resolution. Subtracting each component’s value at 14:00 shows the change in each on a common scale, and an arrow and a label point at the event:

magnetometer <- read_csv("data/magnetometer.csv.gz")

impulse <- magnetometer |>
  filter(
    time >= as.POSIXct("2026-03-20 13:30", tz = "UTC"),
    time < as.POSIXct("2026-03-20 16:00", tz = "UTC")
  ) |>
  pivot_longer(c(bx_nt, by_nt, bz_nt), names_to = "component",
               names_pattern = "b(.)_nt", values_to = "field_nt") |>
  group_by(component) |>
  mutate(change_nt = field_nt - field_nt[time == as.POSIXct("2026-03-20 14:00", tz = "UTC")]) |>
  ungroup()
ggplot(impulse, aes(x = time, y = change_nt, colour = component)) +
  geom_line(linewidth = 0.3) +
  annotate(
    "segment",
    x = as.POSIXct("2026-03-20 13:52", tz = "UTC"), y = 14,
    xend = as.POSIXct("2026-03-20 14:17", tz = "UTC"), yend = 14,
    arrow = arrow(length = unit(0.2, "cm"))
  ) +
  annotate("text", x = as.POSIXct("2026-03-20 13:50", tz = "UTC"), y = 14,
           label = "sudden impulse", hjust = 1, size = 3.5) +
  scale_colour_manual(values = c(x = "#1d3557", y = "#e76f51", z = "#2a9d8f"),
                      labels = c(x = "Bx", y = "By", z = "Bz")) +
  labs(x = "Time (UTC)", y = "Change since 14:00 (nT)", colour = NULL)
Three lines of field change against time from 13:30 to 16:00. All three are nearly flat until 14:20, when the x component jumps by about 16 nanotesla, the z component by about 6 and the y component falls by about 4; all then decay slowly. An arrow labelled sudden impulse points at the jump.
Figure 16.5: The sudden impulse at 14:20 UTC, at one-second resolution, as the change in each field component since 14:00.

The manual colour scale picks three colours that are distinct in hue and in lightness, so the lines stay distinguishable in greyscale.

16.7 Saving figures

ggsave() writes the last figure, or one you name, to a file whose type it takes from the extension. Size it to its final printed width so that the text comes out at the size you chose; Physical Review journals, for example, ask for figures about 8.6 cm wide for one column and 17.8 cm for two. Vector PDF is the format for papers, and the cairo_pdf device embeds the fonts and handles symbols such as Greek letters. PNG at 300 dots per inch suits slides and web pages:

dir.create("scratch", showWarnings = FALSE)

ggsave("scratch/hr-diagram.pdf", hr_plot,
       width = 8.6, height = 8.6, units = "cm", device = cairo_pdf)
ggsave("scratch/hr-diagram.png", hr_plot,
       width = 8.6, height = 8.6, units = "cm", dpi = 300)

If your paper is set in a serif font, theme_physics(base_family = "serif") makes the figures match it. And keep the code that made every figure next to the paper: a figure you can regenerate from the data in one command is a figure you can fix in one command when a referee asks.

16.8 Summary

ggplot2 builds every figure from the same parts, so learning them once lets you make anything. You wrote a reusable journal-style theme, drew a Hertzsprung–Russell diagram with two-dimensional bins on a logarithmic viridis scale and labelled its features with plotmath, pulled an open cluster out of the catalog by position and parallax, projected the whole sky with the Hammer formulas inside mutate(), drew the inner planets from an orbitr simulation on a night-sky background, annotated a geomagnetic sudden impulse, and saved figures at journal widths with ggsave().

16.9 Exercises

  1. Remake the Hertzsprung–Russell diagram with geom_point(size = 0.1, alpha = 0.1) instead of bins. Which features become harder to see, and which easier?
  2. Colour the stars in the sky map by their distance, 1000/ϖ, using a viridis scale. Is there any structure with distance?
  3. Add a line of constant declination at −36.4° to the sky map, in a different colour, to mark the cluster’s latitude.
  4. Fit a straight line to the cluster’s main sequence between colours 0.5 and 2.5 and add it to Figure 16.2. How far above it does the binary sequence sit?
  5. Remake the dimuon spectrum from Chapter 1 with theme_physics(), sized for a single journal column, and save it as a PDF. What has to change to keep the labels legible at that width?