4. Basic figures with ggplot2

Recreating figures from a published sepsis study

For function and argument descriptions, open Reference tables in the Lesson companion.

This lesson uses public figure data from Chenoweth et al. (2024), a study of blood gene expression in adults with sepsis in Kumasi, Ghana. We will make boxplots, patient trajectories, and a heatmap with ggplot2.

The data come from the authors’ Zenodo record. The data notes describe our preparation. These are teaching recreations, so compare them with the published figures as you go.

Allow 35 minutes for the main examples. Leave the interactive plot and six-panel heatmap for extra practice if time is short.

Setup

Each page starts a fresh R session. Run this cell first. In local R, install ggplot2, plotly, and patchwork once with install.packages(c("ggplot2", "plotly", "patchwork")).

samples has one row per blood sample, not per person. Healthy donors have one sample (H); patients have up to eight, linked by patient_id. Visits are measured in hours (h), days (d), and months (m) after enrolment. The factor levels keep them in time order instead of alphabetical order.

PC1 and PC2 summarize gene expression. P1 to P30 are CoGAPS pattern values between 0 and 1, showing how strongly each gene-expression pattern appears in a sample. They are analysis results, not laboratory measurements. heat contains the published heatmap values.

Boxplots over time

A boxplot summarizes a numeric variable within groups. Here the x-axis is visit, the y-axis is PC1, and the fill distinguishes outcomes.

The line is the median and the box spans the middle 50% of samples.

Question: why is there only one box at H, and only survivor boxes after 72h? Check the counts printed in Setup.

Anatomy of a ggplot

ggplot() chooses the data, and aes() maps columns to axes and other visual properties. A geom is the drawing layer: boxes here, or points and lines later.

Read this example as a guide. We build it one piece at a time in the next section.

ggplot(samples, aes(x = visit, y = PC1, fill = outcome)) + # Data and mappings
  geom_boxplot() +                                      # Geom: draw boxes
  scale_fill_manual(values = outcome_colours) +         # Scale: choose colours
  labs(x = "Visit", y = "PC1 score") +                   # Labels: name the axes
  theme_classic()                                      # Theme: set appearance

ggplot() plus geom_boxplot() already makes the simple boxplot above. Colours, labels, and appearance have defaults; the last three lines customize them. Each + adds a plot component. The |> in the table pipeline passes a result to the next function instead. Put + at the end of each line except the last.

Inside aes(), a property varies with a column: fill = outcome assigns colours by outcome. Outside aes(), it is a fixed setting: geom_boxplot(colour = "grey25") gives every box a grey outline. Column names inside aes() are not quoted; fixed colour names are.

Question: which line would you change to rename the y-axis without changing the values plotted?

Build the published version, one step at a time

We will bring the plot closer to Figure 1f. Run each step and look at the result before adding the next.

1. Set the whiskers and box widths.

coef = Inf puts whiskers at the minimum and maximum, as in the paper. Try changing width from 0.7 to 0.4.

2. Set the colours and legend labels.

Change one colour in outcome_colours, then rerun this step.

3. Add labels and a source credit.

The caption includes the source credit; "\n" starts a new line.

4. Set the appearance.

theme_classic() sets the overall style. theme() changes individual parts. Keep that order, or the complete theme replaces your adjustments.

ImportantCompare the samples available

Healthy donors were younger than patients (median age 26 versus 47 years). Patients who died by day 28 have no samples after 72 hours. Later survivor visits include only 41 samples at 28 days, 25 at 6 months, and 14 at 12 months.

The boxes therefore compare changing groups as well as times. They do not show that every patient recovered or establish what caused the differences.

Reuse the figure for another variable

An additional aes() can replace one mapping. Figure 2g uses pattern 23, which the authors link to septic shock.

Pattern 23 is higher in patients who died at each visit through 72 hours. The paper reports an association with 28-day mortality from enrolment; this does not establish causation.

Try it: pattern 15 (Figure 5a)

Allow five minutes. Fill the blanks to plot pattern 15 by visit and outcome, with whiskers extending to the minimum and maximum.

NoteHint

Use P15 for y and outcome for fill. Inf extends the whiskers.

TipSolution
ggplot(samples, aes(x = visit, y = P15, fill = outcome)) +
  geom_boxplot(coef = Inf, position = position_dodge2(preserve = "single")) +
  scale_fill_manual(values = outcome_colours) +
  labs(x = "Visit", y = "Pattern 15 value", fill = "28-day outcome") +
  theme_classic()

Pattern 15 is higher in patients who died at visits through 72 hours. The authors link it to developing neutrophils also seen in severe COVID-19. Compare Figure 5a, or try figure + aes(y = P15).

Follow patients over time

A trajectory joins observations in time order. Figure 6 compares pattern 23, linked to septic shock, with pattern 4, linked to healthy myeloid cells.

Average paths

aggregate() calculates each outcome group’s mean at each visit.

geom_path() follows row order. geom_line() follows x order, which would scramble a path through time. Neither the group mean nor the later visits represent the same number of patients throughout.

A trajectory plot

The plot adds two layers: individual samples, then group means with arrows toward the last visit. data = mean_paths supplies a different dataset for that layer while retaining the x and y mappings.

As in the anatomy example, fill varies by outcome inside aes(), while the grey outline is fixed outside it.

Try changing shape = 21 to 22. Then change stroke = 0.2 to 1.

The survivor mean moves towards the healthy donors. Averages hide individual movement, and later survivor means come from fewer people.

Individual patients

group = patient_id gives each patient a path. facet_wrap() puts outcomes in separate panels.

The lines are tangled because there are more than 100 patients. Can you follow one patient from the first sample to the last?

Explore patients with ggplotly()

ggplotly() converts a ggplot to an interactive HTML plot. highlight_key() links visits from one patient; text supplies hover labels. The package’s message about masked functions is expected.

Hover for the patient and visit. Click a point to highlight the patient’s path; double-click empty space to clear it. Find S67615, a survivor shown in Figure 6b, and follow its path towards the healthy area by 28 days. Click a legend entry to hide a group, or add selectize = TRUE to highlight() to search by patient ID.

Arrows do not survive the ggplotly conversion, so use the hover visit labels. Keep paths for static exports and interactive_paths for interactive HTML. A PNG, SVG, PDF, Word picture, or PowerPoint picture cannot keep these controls. In local R the widget opens in the Viewer or browser; the PDF lesson prints its code. See the Plotly linking guide.

Heatmap: all 30 patterns at a glance

A heatmap uses colour to show values in a grid. Figure 2a has one row per pattern and one column per group and visit. Each z-score compares a group’s mean with that pattern’s mean across the 14 columns. Compare colours within a row: each row is standardized separately.

The factor levels reproduce the published row order, with separate panels for Healthy, Survived, and Died.

Find patterns 23 and 26. Pattern 23 is darker in the Died columns throughout. Pattern 26 is dark early in both patient groups, then fades in survivors. The values are the authors’ group means standardized within each pattern; you could calculate them from samples using group means and scale().

Optional: six heatmaps side by side (Figure 2a–f)

Allow another ten minutes. Each panel uses the same pattern rows, but a separate fill scale. The function below builds one panel; patchwork joins them together.

The panels share the same pattern rows.

AUROC measures separation of survivors from non-survivors at the first five visits: 0.5 is chance and 1 is perfect. The other panels show Spearman correlations with estimated cell proportions, blood counts, chemistry and vital signs, or plasma proteins.

The sequential correlation scales match the paper. For a scale centred on zero, try scale_fill_gradient2(low = "#2166AC", mid = "white", high = "#B2182B"). Pattern 23 has the highest AUROC at the first four visits. For glucose, sodium, and blood urea nitrogen (BUN), it is the darkest row in the chemistry panel; for the Glasgow Coma Scale (GCS), it is the lightest. These are associations, not causes.

Keep a reference handy

The ggplot2 cheatsheet summarizes geoms, scales, facets, labels, and themes on two pages. More are available at Posit’s cheatsheet page.