Session 7: Plotting Further — Bar Charts, Colors, Epicurves, and Facets

Bar charts of counts and values, choosing colors, epidemic curves, facets, and saving plots

NoteIn this session you will learn to
  1. Make bar charts of counts (geom_bar()) and of values you calculated (geom_col())
  2. Order bars sensibly and choose stacked, side-by-side, or 100% bars
  3. Choose colors on purpose with scale_fill_manual()
  4. Make an epidemic curve from dates
  5. Split a plot into small multiples with facet_wrap()
  6. Save plots to files with ggsave()

Before you start: open the workshop folder in Positron (File → Open Folder…) and open student_scripts/Session 7 - Plotting Further_STUDENT.R. This session starts from processed_data/combined_linelist.rds and processed_data/measles_final.rds, the files you made in Session 3. Missed a session? Ready-made copies are already in processed_data/.

Where this session fits. Most data projects go through the same steps, whatever the topic. Today covers Visualize and Save and share (highlighted): more kinds of plots, chosen colors, and saving plots to files you can put in a report.

  1. Import
  2. Inspect
  3. Clean
  4. Combine
  5. Reshape
  6. Summarize
  7. Visualize
  8. Save and share
  9. Automate

Part 1: Set up

Load the packages, import the finished linelist, and put the categories in a sensible order (the same as Session 6):

library(tidyverse)
library(here)
library(rio)

linelist <- import(here("processed_data", "combined_linelist.rds"), trust = TRUE) %>%
  mutate(
    age_cat = fct_relevel(age_cat, "Under 18", "18-29", "30-39", "40-49",
                          "50-59", "60-69", "70-79", "80+", "Unknown"),
    outcome = fct_relevel(outcome, "Recover", "Death", "Unknown")
  )
Note🔍 What this code does
  • library(tidyverse) loads ggplot2 (for plots) and forcats (for fct_ functions) along with the rest of the tidyverse.
  • import(here("processed_data", "combined_linelist.rds"), trust = TRUE) reads the finished linelist from Session 3: 6451 rows. An .rds file can hold any R object, so rio asks you to confirm with trust = TRUE that you trust where it came from.
  • age_cat arrives as plain text. Plots draw text categories in alphabetical order, which would put “Under 18” after “80+”. fct_relevel() turns the column into a factor: categories with an order you choose, youngest to oldest.
  • fct_relevel(outcome, "Recover", "Death", "Unknown") does the same for outcome. The order decides how bars are stacked and the order of the legend.
TipSave your colors once

Saving your colors in a named vector means every plot uses the same color for the same category:

vacc_colors <- c("Yes" = "#2a78d6", "No" = "#eb6834", "Unknown" = "#9a9a95")

You will use these colors in Part 4.

Important✏️ TRY IT 1 (3 min): set up the measles data

Import measles_final.rds as measles, fct_relevel() age_cat and vaccinated (same as Session 6), and save vacc_colors (above).

✅ Check: vacc_colors prints three named colors

measles <- import(here("processed_data", "measles_final.rds"), trust = TRUE) %>%
  mutate(
    age_cat    = fct_relevel(age_cat, "Under 5", "5-9", "10-14", "15+", "Unknown"),
    vaccinated = fct_relevel(vaccinated, "Yes", "No", "Unknown")
  )

vacc_colors <- c("Yes" = "#2a78d6", "No" = "#eb6834", "Unknown" = "#9a9a95")
vacc_colors
      Yes        No   Unknown 
"#2a78d6" "#eb6834" "#9a9a95" 

The same import pipeline as Session 6, plus a named color vector: each name ("Yes", "No", "Unknown") is a category, and each value is its color.

Part 2: Bar charts of counts: geom_bar()

geom_bar() counts the rows in each category for you — you only give it x.

ggplot(data = linelist, mapping = aes(x = hospital_name)) +
  geom_bar()

Vertical bar chart of cases by hospital in gray. The hospital names on the x-axis overlap and are hard to read. Other/Unknown has the most cases (about 2,350), then Regional Medical center (about 1,800).

The labels overlap. Put the categories on the y-axis instead to get horizontal bars:

ggplot(data = linelist, mapping = aes(y = hospital_name)) +
  geom_bar()

Horizontal bar chart of cases by hospital in gray. The hospital names on the y-axis are now easy to read, but the bars are in alphabetical order.

Note🔍 What this code does
  • ggplot(data = linelist, mapping = aes(x = hospital_name)) sets up the plot: which data to use, and which column goes on the x-axis. On its own it draws an empty frame.
  • + geom_bar() adds a layer of bars. geom_bar() counts the rows for each hospital itself, so you don’t give it a y. Other/Unknown is the tallest bar, with 2354 cases.
  • The seven hospital names are long, so on the x-axis they overlap. aes(y = hospital_name) puts them on the y-axis instead: horizontal bars, with labels you can read.
  • hospital_name is text, so the bars are in alphabetical order. The next step fixes that.

Order the bars

Alphabetical order rarely helps. fct_infreq() orders by count (most common first), and fct_rev() flips it so the longest bar is at the top:

ggplot(data = linelist, mapping = aes(y = fct_rev(fct_infreq(hospital_name)))) +
  geom_bar(fill = "#2a78d6") +
  labs(title = "Cases by hospital", x = "Number of cases", y = NULL) +
  theme_minimal()

Horizontal bar chart titled Cases by hospital in blue, sorted from most to fewest cases: Other/Unknown, Regional Medical center, Military Hospital, Central Hospital, St. Mark's Maternity Hospital, HMO Health, and Premiere Health.

Tip🧩 Reading a function call

Here is the core of the plot you just made, taken apart:

ggplot(data = linelist, mapping = aes(y = fct_rev(fct_infreq(hospital_name)))) + geom_bar(fill = "#2a78d6")

Piece What it is What it does
ggplot(...) the function that starts every plot sets up an empty plot
data = linelist a named argument of ggplot() the data to plot
mapping = aes(...) a named argument, filled in by the aes() function links columns to parts of the plot (“aesthetics”)
y = fct_rev(fct_infreq(hospital_name)) an argument of aes() puts the hospitals on the y-axis, in the order of their counts
+ the plus sign adds the next layer to the plot
geom_bar(...) a function that adds a layer draws one bar per hospital, counting its rows
fill = "#2a78d6" an argument of geom_bar(), outside aes() colors every bar the same blue

Inside the brackets, R works from the inside out: fct_infreq() orders the hospitals by count, then fct_rev() reverses that order. The + signs then build the plot layer by layer, from left to right: first the empty plot, then the bars, then the labels and the theme.

Note🔍 What this code does
  • fct_infreq(hospital_name) turns the hospital names into categories ordered by how often they appear, most common first.
  • fct_rev() reverses that order. On a horizontal chart the first category is drawn at the bottom, so reversing it puts the longest bar (Other/Unknown, 2354 cases) at the top.
  • geom_bar(fill = "#2a78d6") colors every bar blue. fill is outside aes() here, so it’s one fixed color, not linked to a column.
  • labs() sets the title and the axis titles. y = NULL removes the y-axis title: the hospital names speak for themselves.
  • theme_minimal() removes the gray background and keeps light grid lines.

Fill by a second variable

Map fill to split each bar. The position argument controls how the pieces are arranged:

# "stack" (the default): counts, stacked
ggplot(data = linelist, mapping = aes(x = age_cat, fill = outcome)) +
  geom_bar(position = "stack")

Stacked bar chart of case counts by age group, split by outcome. The Under 18 group is by far the largest (about 4,000 cases), so outcomes in the older groups are hard to compare.

# "fill": every bar is 100% — compares PROPORTIONS across groups
ggplot(data = linelist, mapping = aes(x = age_cat, fill = outcome)) +
  geom_bar(position = "fill")

100% stacked bar chart of outcome by age group: each bar is split into Recover, Death, and Unknown and reaches the same height, so proportions can be compared. The small older groups vary the most.

# "dodge": side by side — compares COUNTS within each group
ggplot(data = linelist, mapping = aes(x = age_cat, fill = outcome)) +
  geom_bar(position = "dodge")

Bar chart with side-by-side bars for Recover, Death, and Unknown in each age group. Under 18 has the tallest bars, and deaths outnumber recoveries in most age groups.

Note🔍 What this code does
  • fill = outcome is inside aes(), so it’s linked to a column: each bar is split into one colored piece per outcome, and ggplot adds a legend. These are ggplot’s default colors; in Part 4 you choose your own.
  • position = "stack" piles the pieces on top of each other, so the bar height is the number of cases. Under 18 has 3962 cases and 80+ only 1, so the older groups are hard to see.
  • position = "fill" stretches every bar to the same height, from 0 to 1 (0% to 100%). You compare proportions: what share of each age group recovered, died, or has an unknown outcome.
  • position = "dodge" puts the pieces side by side. You compare counts within each group: in most age groups the Death bar is taller than the Recover bar (Under 18: 1755 deaths, 1322 recoveries).

The 100% "fill" version. The stacked version mostly shows that there are many more young patients than old ones, so the small bars for older groups are hard to compare.

Important✏️ TRY IT 2 (3 min): cases by district

Make a horizontal bar chart of measles cases by district, longest bar on top.

✅ Check: North is at the top; Unknown is at the bottom

ggplot(data = measles, mapping = aes(y = fct_rev(fct_infreq(district)))) +
  geom_bar(fill = "#2a78d6") +
  labs(title = "Measles cases by district", x = "Number of cases", y = NULL) +
  theme_minimal()

Horizontal bar chart of measles cases by district in blue, longest at the top: North (342), South (284), East (223), West (170), Central (110), and Unknown (34).

fct_infreq() puts North (342 cases) first, and fct_rev() moves it to the top. Unknown (34 cases) ends up at the bottom.

Note📖 Good to know
  • Inside or outside aes()? Inside aes(), a setting is linked to a column and changes from bar to bar (aes(fill = outcome)). Outside, it’s one fixed value for everything (geom_bar(fill = "#2a78d6")).
  • A common mistake is a color name inside aes(): aes(fill = "blue"). ggplot treats “blue” as a category called “blue”, draws it in its first default color (a salmon red), and adds a legend for it.

Part 3: Bar charts of values: geom_col()

When you have already calculated the numbers (with count() or summarise() from Session 5), use geom_col() and give it both x and y:

death_by_age <- linelist %>%
  filter(outcome != "Unknown", age_cat != "Unknown") %>%
  group_by(age_cat) %>%
  summarise(
    n         = n(),
    pct_death = mean(outcome == "Death") * 100
  )

death_by_age
# A tibble: 8 × 3
  age_cat      n pct_death
  <fct>    <int>     <dbl>
1 Under 18  3077      57.0
2 18-29     1146      56.5
3 30-39      435      58.9
4 40-49      190      55.3
5 50-59       53      54.7
6 60-69       24      33.3
7 70-79        6      50  
8 80+          1       0  
ggplot(data = death_by_age, mapping = aes(x = age_cat, y = pct_death)) +
  geom_col(fill = "#2a78d6") +
  labs(title = "Case fatality by age group", x = "Age group", y = "Deaths (% of cases)") +
  theme_minimal()

Bar chart of the percentage of cases who died in each age group: 55 to 59% for every group under 60, 33% for 60 to 69, 50% for 70 to 79 (only 6 patients), and 0% for 80 and over (1 patient).

Note🔍 What this code does
  • The first block makes a small table, death_by_age. filter() leaves out patients with an unknown outcome or age group; group_by(age_cat) and summarise() then give one row per age group.
  • n = n() counts the patients in each group. mean(outcome == "Death") * 100 is the percentage who died: outcome == "Death" is TRUE or FALSE for each patient, and the mean of TRUE/FALSE values is the share that are TRUE. For Under 18 that’s 57.0%.
  • Printing death_by_age shows the 8 rows, so you can check the numbers before you plot them.
  • geom_col() draws the numbers as they are: one bar per row, with x = age_cat and y = pct_death. Nothing is counted; the bar height is the percentage.
Notegeom_bar() or geom_col()?

geom_bar() counts rows for you (one row per patient): give it x only. geom_col() draws numbers you already have (one row per bar): give it x and y.

fct_reorder(CATEGORY, NUMBER) sorts the bars by the number.

Not much. Check n in death_by_age: the 70–79 bar is based on 6 patients and the 80+ bar on just 1. One more death or recovery would change those percentages a lot. Always look at how many cases are behind a percentage.

Important✏️ TRY IT 3 (5 min): case rates by district
  1. Calculate cases per 10,000 people by district (Session 5), leaving out “Unknown”.
  2. Plot it with geom_col(), using x = fct_reorder(district, rate_per_10k).

✅ Check: bars from Central (lowest, 5.2) to East (highest, 22.8)

# a)
district_rates <- measles %>%
  filter(district != "Unknown") %>%
  count(district, population) %>%
  mutate(rate_per_10k = round(n / population * 10000, 1))

district_rates
  district population   n rate_per_10k
1  Central     210000 110          5.2
2     East      98000 223         22.8
3    North     185000 342         18.5
4    South     142000 284         20.0
5     West      76500 170         22.2
# b)
ggplot(data = district_rates, mapping = aes(x = fct_reorder(district, rate_per_10k), y = rate_per_10k)) +
  geom_col(fill = "#2a78d6") +
  labs(
    title = "Measles cases per 10,000 people by district",
    x     = "District",
    y     = "Cases per 10,000 people"
  ) +
  theme_minimal()

Bar chart of measles cases per 10,000 people by district, sorted from lowest to highest: Central 5.2, North 18.5, South 20.0, West 22.2, and East 22.8.

count() makes one row per district, so geom_col() is the right choice. North has the most cases, but Central has the largest population, so the rates tell a different story: East (22.8) and West (22.2) are highest, Central (5.2) is lowest.

Part 4: Choosing colors

ggplot’s default colors are fine for exploring, but for a report choose colors on purpose:

  • Use colors that people with color-vision deficiency can tell apart. Avoid red vs green (the most common problem pair) and two shades of the same color. Blue (#2a78d6) and orange (#eb6834) are a safe pair
  • Give “Unknown” or “Other” a gray (#9a9a95), so it doesn’t compete with the real categories
  • Keep the same color for the same category in every plot of a report

scale_fill_manual() (for fill) and scale_color_manual() (for color) set the colors by name:

outcome_colors <- c("Recover" = "#2a78d6", "Death" = "#eb6834", "Unknown" = "#9a9a95")

ggplot(data = linelist, mapping = aes(x = age_cat, fill = outcome)) +
  geom_bar(position = "fill", color = "white") +
  scale_fill_manual(values = outcome_colors) +
  scale_y_continuous(labels = scales::percent) +
  labs(
    title = "Outcome by age group",
    x     = "Age group",
    y     = "Percent of cases",
    fill  = "Outcome"
  ) +
  theme_minimal()

100% stacked bar chart of outcome by age group with chosen colors: blue for Recover, orange for Death, and gray for Unknown, with a percent y-axis and a minimal theme.

Note🔍 What this code does
  • outcome_colors is a named vector: each name (“Recover”, “Death”, “Unknown”) is a category, and each value is its color. Saving it once lets you reuse it in every plot.
  • scale_fill_manual(values = outcome_colors) matches the colors to the categories by name, so Recover is always blue, even in a plot where some outcomes are missing.
  • geom_bar(position = "fill", color = "white") makes 100% bars, and color = "white" draws a thin white line between the pieces.
  • scale_y_continuous(labels = scales::percent) shows the y-axis values 0.25, 0.50, … as 25%, 50%, ….
  • In labs(), fill = "Outcome" sets the title of the legend.
TipNeed more colors?

The viridis scales are built into ggplot2 and are colorblind-friendly: try scale_fill_viridis_d() for categories.

Rotate long labels

If you keep labels on the x-axis, rotate them so they don’t overlap:

ggplot(data = linelist, mapping = aes(x = hospital_name)) +
  geom_bar(fill = "#2a78d6") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

Vertical bar chart of cases by hospital in blue, with the hospital names rotated 45 degrees so they no longer overlap.

Important✏️ TRY IT 4 (4 min): vaccination by age group

Make a 100% bar chart of vaccinated by age_cat, with vacc_colors, a percent y-axis, labels, and theme_minimal().

✅ Check: every bar reaches 100%; “Yes” is blue in every bar

ggplot(data = measles, mapping = aes(x = age_cat, fill = vaccinated)) +
  geom_bar(position = "fill", color = "white") +
  scale_fill_manual(values = vacc_colors) +
  scale_y_continuous(labels = scales::percent) +
  labs(
    title = "Vaccination status of measles cases by age group",
    x     = "Age group",
    y     = "Percent of cases",
    fill  = "Vaccinated"
  ) +
  theme_minimal()

100% stacked bar chart of measles vaccination status by age group. In every age group most cases were unvaccinated (orange), and about a quarter were vaccinated (blue); gray shows unknown status.

position = "fill" makes every bar 100%, and because vacc_colors is a named vector, “Yes” is always blue, “No” orange, and “Unknown” gray.

Note📖 Good to know
  • About 1 in 12 men and 1 in 200 women have some form of color-vision deficiency, so in a room of 30 people, someone probably can’t tell red from green.
  • Don’t rely on color alone: clear titles, axis labels, and a sensible order make a plot readable even in black and white.

Part 5: Epidemic curves

An epidemic curve (epicurve) shows the number of new cases over time — the most important plot in outbreak investigation. It is a histogram of a date column:

ggplot(data = linelist, mapping = aes(x = onset_date)) +
  geom_histogram(binwidth = 7, fill = "#2a78d6", color = "white")

Weekly epidemic curve of all onset dates: a small cluster in late 2012 and early 2013, a gap, then the main outbreak from mid-2014 that peaks at about 300 cases per week in September 2014.

Note🔍 What this code does
  • aes(x = onset_date) puts the date of symptom onset on the x-axis. geom_histogram() sorts the dates into bins and counts the cases in each one.
  • Dates are counted in days, so binwidth = 7 makes each bin, and so each bar, one week long.
  • fill = "#2a78d6", color = "white" gives blue bars with a white outline, so neighbouring weeks are easy to tell apart.
  • R warns that it removed 281 rows: those cases have no onset date, so they can’t be placed on a time axis. The warning is expected.
  • The x-axis runs from April 2012 to April 2015. Look at the left end before reading on.

538 onset dates fall in 2012–2013, long before the outbreak — and every one of them belongs to a case ID that appears more than once (the duplicate IDs from Session 3), usually with the same day and month but a different year. They are almost certainly data-entry errors in the year. Plots reveal problems tables hide: look at the whole range first!

Zoom in on the outbreak and format the date axis:

linelist %>%
  filter(onset_date >= as.Date("2014-01-01")) %>%
  ggplot(mapping = aes(x = onset_date)) +
  geom_histogram(binwidth = 7, fill = "#2a78d6", color = "white") +
  scale_x_date(date_breaks = "2 months", date_labels = "%b\n%Y") +
  labs(
    title    = "Epidemic curve: weekly cases by date of symptom onset",
    subtitle = "Onset dates from 2014 onward",
    x        = "Week of onset",
    y        = "Number of cases"
  ) +
  theme_minimal()

Epidemic curve of weekly cases from 2014 onward. Cases rise from May 2014 to a peak of about 300 per week in September 2014, then decline slowly through April 2015.

Note🔍 What this code does
  • filter(onset_date >= as.Date("2014-01-01")) keeps cases with an onset on or after 1 January 2014. as.Date() turns the text into a date so R can compare. Rows with no onset date are dropped too, which leaves 5632 cases.
  • The data is piped into ggplot(), so you don’t write data =: the pipe passes it in as the first argument.
  • scale_x_date(date_breaks = "2 months", date_labels = "%b\n%Y") puts a label every two months. %b is the short month name, \n starts a new line, and %Y is the year, so a label reads “Sep” above “2014”. (%d is the day and %B the full month name.)
  • labs() adds a title, a subtitle, and axis titles. The busiest week, in September 2014, has 304 cases.

Epicurve by outcome

linelist %>%
  filter(onset_date >= as.Date("2014-01-01")) %>%
  ggplot(mapping = aes(x = onset_date, fill = outcome)) +
  geom_histogram(binwidth = 7, color = "white") +
  scale_fill_manual(values = outcome_colors) +
  scale_x_date(date_breaks = "2 months", date_labels = "%b\n%Y") +
  labs(x = "Week of onset", y = "Number of cases", fill = "Outcome") +
  theme_minimal()

Epidemic curve of weekly cases from 2014 onward with each bar split by outcome: blue for Recover, orange for Death, gray for Unknown. All three outcomes rise and fall with the outbreak.

Note🔍 What this code does
  • fill = outcome inside aes() splits each week’s bar by outcome, and scale_fill_manual(values = outcome_colors) uses the same colors as in Part 4.
  • The fixed fill = "#2a78d6" is gone from geom_histogram(). A fixed fill there would paint every bar blue and hide the outcome colors.
Important✏️ TRY IT 5 (5 min): the measles epicurve

Make a weekly epicurve of measles report_date, filled by vaccinated, with vacc_colors and scale_x_date(date_breaks = "1 month", date_labels = "%b"). Save it as measles_epicurve — you will need it in Part 7. Hint: filter(!is.na(report_date)) first. When did the outbreak peak?

✅ Check: the peak is in the second half of March (about 115 cases in one week)

measles_epicurve <- measles %>%
  filter(!is.na(report_date)) %>%
  ggplot(mapping = aes(x = report_date, fill = vaccinated)) +
  geom_histogram(binwidth = 7, color = "white") +
  scale_fill_manual(values = vacc_colors) +
  scale_x_date(date_breaks = "1 month", date_labels = "%b") +
  labs(
    title = "Measles cases by week of report, 2024",
    x     = "Week of report",
    y     = "Number of cases",
    fill  = "Vaccinated"
  ) +
  theme_minimal()

measles_epicurve

Weekly epidemic curve of measles cases in 2024 by week of report, split by vaccination status. Cases rise from February, peak in the second half of March at about 115 cases in one week, and fall through June. Most cases each week were unvaccinated (orange).

The outbreak peaked in the second half of March 2024, with 117 cases in the peak week. Saving the plot as an object means it only appears when you print it (the last line).

Note📖 Good to know
  • Which date? Epicurves usually use the date of symptom onset, because it’s closest to when people were infected. The date a case was reported comes later, and the delay varies from case to case.
  • The last weeks often look lower than they really are. Recent cases may not have been reported yet. Keep that in mind before saying an outbreak is ending.

Part 6: Facets

facet_wrap() splits one plot into small multiples — one panel per category, all with the same axes so they are easy to compare:

linelist %>%
  filter(onset_date >= as.Date("2014-01-01"), hospital_name != "Other/Unknown") %>%
  ggplot(mapping = aes(x = onset_date)) +
  geom_histogram(binwidth = 7, fill = "#2a78d6", color = "white") +
  facet_wrap(~ hospital_name) +
  scale_x_date(date_breaks = "4 months", date_labels = "%b\n%Y") +
  labs(title = "Weekly cases by hospital", x = "Week of onset", y = "Number of cases") +
  theme_minimal()

Four small epidemic curves on the same axes, one per hospital: Central Hospital, Military Hospital, Regional Medical center, and St. Mark's Maternity Hospital. Regional Medical center has the largest outbreak, peaking at about 90 cases per week in September 2014.

Note🔍 What this code does
  • filter() keeps onset dates from 2014 and leaves out the “Other/Unknown” hospital.
  • facet_wrap(~ hospital_name) draws one small epicurve per hospital. Read the ~ as “by”: “wrap the plot by hospital name”.
  • All panels share the same x- and y-axes, so a taller bar really means more cases, whichever panel it’s in.
  • There are only four panels. HMO Health and Premiere Health have no onset dates from 2014 (all of theirs are in 2012–2013), so the filter leaves nothing to plot for them.
  • date_breaks = "4 months" labels the axis less often, because each panel is narrow.

Facets work with any plot:

linelist %>%
  filter(gender != "Unknown") %>%
  ggplot(mapping = aes(x = age_years)) +
  geom_histogram(binwidth = 5, fill = "#2a78d6", color = "white") +
  facet_wrap(~ gender) +
  labs(title = "Age distribution by gender", x = "Age (years)", y = "Number of cases") +
  theme_minimal()

Two age histograms side by side, for female and male patients. Female patients are mostly under 25, while male ages are spread more widely, up to about 75.

Note🔍 What this code does
  • The same facet_wrap() works on any plot: here a histogram of age, with each bar covering 5 years (binwidth = 5).
  • filter(gender != "Unknown") leaves out the 304 patients with unknown gender, so 6147 are plotted.
  • facet_wrap(~ gender) gives one panel for female and one for male patients, on the same axes, so you can compare the shapes directly.
Note
  • facet_wrap(~ hospital_name, ncol = 2) sets the number of columns
  • facet_wrap(~ hospital_name, scales = "free_y") lets each panel have its own y-axis (careful: it makes panels harder to compare)
  • facet_grid(gender ~ outcome) makes a grid with one variable for rows and one for columns
Important✏️ TRY IT 6 (4 min): facets

Facet your measles epicurve by district (leave out “Unknown”). Did every district peak at the same time?

✅ Check: five panels; every district peaks in March

measles %>%
  filter(!is.na(report_date), district != "Unknown") %>%
  ggplot(mapping = aes(x = report_date, fill = vaccinated)) +
  geom_histogram(binwidth = 7, color = "white") +
  facet_wrap(~ district) +
  scale_fill_manual(values = vacc_colors) +
  scale_x_date(date_breaks = "2 months", date_labels = "%b") +
  labs(
    title = "Measles cases by week of report and district, 2024",
    x     = "Week of report",
    y     = "Number of cases",
    fill  = "Vaccinated"
  ) +
  theme_minimal()

Five small weekly epidemic curves of measles cases, one per district, with bars colored by vaccination status. Every district peaks in March 2024, and North has the most cases.

Roughly, yes: every district peaks in March, at about the same time as the overall outbreak. North has the most cases (its busiest week has 39).

Part 7: Saving plots

ggsave() saves the last plot you made, or a plot object you name. Save the plot as an object first:

epicurve <- linelist %>%
  filter(onset_date >= as.Date("2014-01-01")) %>%
  ggplot(mapping = aes(x = onset_date)) +
  geom_histogram(binwidth = 7, fill = "#2a78d6", color = "white") +
  labs(title = "Weekly cases", x = "Week of onset", y = "Number of cases") +
  theme_minimal()

Then save it to the outputs/ folder:

ggsave(here("outputs", "epicurve.png"), plot = epicurve,
       width = 8, height = 5, dpi = 300)
Note🔍 What this code does
  • epicurve <- linelist %>% ... + theme_minimal() saves the plot as an object instead of showing it. Nothing appears until you print it (type epicurve) or save it.
  • ggsave(here("outputs", "epicurve.png"), plot = epicurve, ...) writes the plot to a file. here() builds the path, as in Session 1, and plot = epicurve says which plot to save. Without plot =, ggsave() saves the last plot you looked at.
  • The file type comes from the ending: .png for slides and documents, .pdf for print.
  • width and height are in inches. dpi = 300 (dots per inch) is print quality: this file is 8 × 300 = 2400 pixels wide and 5 × 300 = 1500 high.
  • Save plots in their own folder (here, outputs/) so they don’t get mixed up with data.
Note📖 Good to know
  • Text in a saved plot is sized in points, like in a word processor. On a small plot (width = 4), the text takes up more of the picture; on a large one (width = 12), less. If the labels look too big or too small in the file, change width and height, not dpi.
  • dpi only changes how sharp the picture is (how many pixels it has), not how big the text looks.
Important✏️ TRY IT 7 (3 min): save a plot

Save your measles epicurve to outputs/measles_epicurve.png, 8 inches wide, 5 inches high, dpi = 300.

✅ Check: open the file from the Explorer (outputs folder). Does it look right?

ggsave(here("outputs", "measles_epicurve.png"), plot = measles_epicurve,
       width = 8, height = 5, dpi = 300)

Because you saved the plot as measles_epicurve in Part 5, you can pass it to plot =. If the text looks too large or small in the file, change width and height.

Tip⭐ Bonus
  1. Make a bar chart of the percentage of measles cases who died in each age group (summarise() first, then geom_col()).
  2. Try scale_fill_viridis_d() instead of scale_fill_manual() on one of your plots.
  3. Brought your own data? Make a bar chart, a plot over time (if you have dates), and a faceted plot, and save one of them with ggsave().

See the solutions file for the code.

Extra: box plots with summary labels (optional)

This optional, advanced example calculates the median and quartiles for each group with summarise(), turns them into text, and adds them to the plot with geom_text() — combining Sessions 4, 5, and 6.

# 1. Summary statistics for each gender and outcome
box_stats <- linelist %>%
  filter(gender != "Unknown", outcome != "Unknown") %>%
  group_by(gender, outcome) %>%
  summarise(
    median = median(age_years, na.rm = TRUE),
    q1     = quantile(age_years, 0.25, na.rm = TRUE),
    q3     = quantile(age_years, 0.75, na.rm = TRUE),
    .groups = "drop"
  ) %>%
  mutate(label = paste0("Median: ", round(median, 1), "\n",
                        "Q1: ", round(q1, 1), "\n",
                        "Q3: ", round(q3, 1)))

# 2. The plot, with the labels placed beside each box
linelist %>%
  filter(gender != "Unknown", outcome != "Unknown") %>%
  ggplot(mapping = aes(x = gender, y = age_years)) +
  geom_boxplot(fill = "#2a78d6", alpha = 0.3, width = 0.35) +
  geom_text(
    data = box_stats,
    mapping = aes(x = gender, y = q3, label = label),
    nudge_x = 0.22, hjust = 0, vjust = 0, size = 2.8, color = "gray30"
  ) +
  facet_wrap(~ outcome) +
  scale_x_discrete(expand = expansion(add = c(0.4, 0.9))) +   # room on the right for the labels
  labs(
    title    = "Age distribution by gender and outcome",
    subtitle = "Labels show the median and quartiles",
    x        = "Gender",
    y        = "Age (years)"
  ) +
  theme_minimal()

Box plots of age by gender in two panels, Recover and Death, each labeled with its median and quartiles. Females have a median of 11 (Q1 5, Q3 18 to 19) and males a median of 17 (Q1 8, Q3 28 to 29), nearly the same for both outcomes.

Key points

  • geom_bar() counts rows for you; geom_col() draws numbers you already calculated.
  • Order bars with fct_infreq() / fct_reorder(), and use horizontal bars (aes(y = ...)) for long labels.
  • position = "stack", "fill" (100%, compares proportions), or "dodge" (side by side, compares counts).
  • Choose colors on purpose: colorblind-safe pairs (not red vs green), gray for “Unknown”, and a named color vector with scale_fill_manual() so each category keeps its color.
  • An epicurve is a weekly histogram of a date column; format the axis with scale_x_date(). Look at the whole date range first — plots reveal data errors.
  • facet_wrap(~ COLUMN) makes small multiples with shared axes.
  • Save a plot as an object, then ggsave(here("outputs", "file.png"), plot = ..., width, height, dpi).

Next: Session 8 — Programming (optional). Write your own functions, use if/else, and loop over groups — for example, to save one epidemic curve per hospital automatically.