Make bar charts of counts (geom_bar()) and of values you calculated (geom_col())
Order bars sensibly and choose stacked, side-by-side, or 100% bars
Choose colors on purpose with scale_fill_manual()
Make an epidemic curve from dates
Split a plot into small multiples with facet_wrap()
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.
Import
Inspect
Clean
Combine
Reshape
Summarize
Visualize
Save and share
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):
👀 Follow along 1.1 — Load tidyverse, here, and rio; import combined_linelist.rds as linelist, and fct_relevel()age_cat and outcome (same as Session 6).
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:
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:
👀 Follow along 2.2 — Order the bars with fct_rev(fct_infreq(hospital_name)), and add a fill color and labs().
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()
Tip🧩 Reading a function call
Here is the core of the plot you just made, taken apart:
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:
👀 Follow along 2.3 — x = age_cat, fill = outcome, with position = "stack", "fill", and "dodge" (the next three code blocks).
# "stack" (the default): counts, stackedggplot(data = linelist, mapping =aes(x = age_cat, fill = outcome)) +geom_bar(position ="stack")
# "fill": every bar is 100% — compares PROPORTIONS across groupsggplot(data = linelist, mapping =aes(x = age_cat, fill = outcome)) +geom_bar(position ="fill")
# "dodge": side by side — compares COUNTS within each groupggplot(data = linelist, mapping =aes(x = age_cat, fill = outcome)) +geom_bar(position ="dodge")
Note🔍 What this code does
fill = outcome is insideaes(), 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).
Note🤔 Think about it: which version answers “do older patients die more often?”
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
NoteShow solution
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()
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:
👀 Follow along 3.1 — Create death_by_age (the percentage who died in each age group), then plot it with geom_col().
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()
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 xandy.
fct_reorder(CATEGORY, NUMBER) sorts the bars by the number.
Note🤔 Think about it: how much should we trust the 70–79 and 80+ bars?
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
Calculate cases per 10,000 people by district (Session 5), leaving out “Unknown”.
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)
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()
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:
👀 Follow along 4.1 — Save outcome_colors, then make a 100% bar chart of outcome by age_cat with scale_fill_manual(), a white outline, and a percent y-axis.
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()
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:
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
NoteShow solution
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()
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:
👀 Follow along 5.1 — geom_histogram() of onset_date with binwidth = 7. What’s going on before 2014?
ggplot(data = linelist, mapping =aes(x = onset_date)) +geom_histogram(binwidth =7, fill ="#2a78d6", color ="white")
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.
Note🤔 Think about it: what is going on before 2014?
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:
👀 Follow along 5.2 — Keep onset dates from 2014, and add scale_x_date() and labs().
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()
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
👀 Follow along 5.3 — Fill the epicurve by outcome with outcome_colors.
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()
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)
NoteShow solution
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
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:
👀 Follow along 6.1 — The epicurve with facet_wrap(~ hospital_name), leaving out “Other/Unknown”.
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()
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:
👀 Follow along 6.2 — An age histogram with facet_wrap(~ gender), leaving out “Unknown”.
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()
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
NoteShow solution
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()
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:
👀 Follow along 7.1 — Save the epicurve as an object, then ggsave() it to outputs/epicurve.png (the next two code blocks).
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()
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?
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
Make a bar chart of the percentage of measles cases who died in each age group (summarise() first, then geom_col()).
Try scale_fill_viridis_d() instead of scale_fill_manual() on one of your plots.
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 outcomebox_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 boxlinelist %>%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 labelslabs(title ="Age distribution by gender and outcome",subtitle ="Labels show the median and quartiles",x ="Gender",y ="Age (years)" ) +theme_minimal()
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.