6  Lab: Data Visualisation with ggplot

Author

Gabriele Filomena

Published

November 1, 2026

ImportantMake sure you have the latest version of this lab

This lab was updated in late October 2026. If you opened or copied it before then, you may have an old version.

  1. Download the latest version. Open the lab on GitHub and click the Download raw file button (the arrow icon at the top right of the file). Alternatively, right-click this link and choose Save link as…. Keep the name 05.Visualisation.qmd.
  2. Put it in labs. In RStudio, in the Files pane, open the labs folder, click Upload, choose the file you downloaded and click OK. When RStudio asks, confirm that you want to replace the existing file.
  3. If you want, copy it to myLabs: open it and use File -> Save As..., as usual. If you already have notes in an old copy in myLabs, give the new copy a different name (e.g. 05.Visualisation_new.qmd) so you don’t lose them.

Open this lab in RStudio: in the Files pane, click labs and then 05.Visualisation.qmd. Save your own copy in myLabs (File -> Save As...) and work on the copy. Work through it from top to bottom, running each code chunk and adding your notes and answers in the file. (First time? See the Setup guide.)

This lab uses two datasets. The Census 2021 district data are already in your data folder. The Family Resources Survey (FRS) is not in the repository because it is licensed: if you haven’t done it already in Lab 01, download FRS16-17_labels.csv from the FRS page on Canvas and upload it to a new folder data/FRS in RStudio (see Setup, section 5). You don’t need to change any of the file paths in the code.

The lecture’s slides can be found here.

6.1 Part 1 - Visualisation: ggplot2 Functions and Arguments

For this session you need the following libraries: tidyverse (which includes ggplot2, dplyr, tidyr and forcats), kableExtra, ggridges, RColorBrewer, broom, scales, corrplot, vtable. They are all already installed in your codespace; the code below loads each one when it is needed.

The ggplot2 package in R is one of the most powerful tools for creating publication-quality visualisations. It uses a layered approach to building plots, starting with data, then adding mappings, geometries, and other components.

A ggplot2 plot is built step by step:

ggplot(data, aes(x = <X-axis variable>, y = <Y-axis variable>, <other aesthetics>)) +
 <geom_function()> +
 <scales/themes/other layers>

6.1.1 ggplot()

  • Initializes the plotting system.
  • Main arguments:
    • data: A data frame containing the variables to be plotted.
    • aes(): Aesthetic mappings to connect data variables to visual properties like x, y, color, fill, size, etc.
library(ggplot2)
Warning: package 'ggplot2' was built under R version 4.5.1

Example:

Let’s load the data first:

census_data <- read.csv("../data/Census2021/EW_DistrictPercentages.csv")

Plotting Number of residents vs age (mean).

ggplot(data = census_data, aes(x = Residents, y = mean_age)) +
 geom_point()

6.1.2 Geometries in ggplot2

You can plot the following geometries in ggplot:

Geometry Function Use Case
Point geom_point() Scatterplots
Line geom_line() Line plots
Bar geom_bar() Bar charts
Histogram geom_histogram() Histograms
Boxplot geom_boxplot() Boxplots
Density geom_density() Density plots
Smooth geom_smooth() Add regression or smoothing lines

Example: Scatterplot with geom_point()

ggplot(census_data, aes(x = Residents, y = mean_age, color = factor(Region))) +
 geom_point(size = 3)

6.1.3 Aesthetics: aes()

  • Maps data variables to visual properties.
  • Common aesthetics:
    • x: X-axis variable.
    • y: Y-axis variable.
    • color: Changes point/line colors based on a variable.
    • fill: Fills bars/areas based on a variable.
    • size: Controls the size of points/lines.

Example: Adding color and size aesthetics

ggplot(census_data, aes(x = Residents, y = mean_age, color = factor(Region), size = pct_Very_bad_health)) +
 geom_point()

NoteQuestion

What’s missing in the plot above? How can this be improved?

6.1.4 Faceting: facet_*

Faceting splits data into subsets and creates multiple small plots.

Function Description
facet_wrap(~var) Wraps plots across rows/columns.
facet_grid(row ~ col) Creates a grid layout for plots.

Faceting is a technique to create multiple plots based on subsets of your data. It is particularly useful for comparing relationships or distributions across categories. By breaking down a dataset into smaller pieces according to a categorical variable, faceting helps visualise data trends or differences within subgroups. For instance, facet_wrap(~ Region) creates individual plots for each category in the Region variable, aligning them into rows and columns. Alternatively, facet_grid(row ~ col) creates a more structured layout, where two categorical variables determine the rows and columns of the grid.

Faceting is essential when dealing with data that needs to be compared across multiple dimensions. For example, a scatterplot faceted by sex can show how a relationship differs for males and females. Similarly, faceted histograms can reveal differences in the distribution of a variable across categories.

ggplot(census_data, aes(x = Residents, y = mean_age)) +
 geom_point() +
 facet_wrap(~Region)

NoteQuestion

What are the issues here?

6.1.5 Themes (theme_*)

Themes control the overall appearance of the plot.

Function Effect
theme_minimal() Simple and clean theme.
theme_classic() Classic-style plots.
theme_dark() Dark background.
theme_void() Minimal with no axes or grids.

Applying a theme

ggplot(data = census_data, aes(x = Residents, y = mean_age)) +
 geom_point() +
 theme_void() +
 labs(title = "Visualisation with Void Theme")

NoteQuestion

What do you think? Is this any good?

6.1.6 Scales

Scales adjust color, size, and axis properties.

Scale Description
scale_color_manual() Customizes colors for lines/points.
scale_fill_brewer() Predefined color palettes for fills.
scale_x_continuous() Modifies X-axis properties.
scale_y_continuous() Modifies Y-axis properties.

scale_color functions modify the outline color of elements like points, lines, or the border of shapes, while scale_fill functions modify the interior fill color of shapes like bars, tiles, or boxes. Both are used to control aesthetics based on a variable mapped in aes() but apply to different visual aspects of the plot.

Example: Customizing axis and colors

The RColorBrewer library provides pre-defined color palettes specifically designed for data visualisation, ensuring clarity and accessibility. It includes three families of palettes, and you should pick the family that matches your variable:

  • Sequential (e.g. Blues, YlOrRd): for ordered values, from low to high (e.g. % of residents with no qualifications, or health from Very Good to Very Bad).
  • Diverging (e.g. RdBu, PuOr): for values with a meaningful midpoint (e.g. change above or below zero, a correlation from -1 to 1).
  • Qualitative (e.g. Set2, Dark2): for categories with no order (e.g. Region).

Have a look at: https://r-graph-gallery.com/38-rcolorbrewers-palettes.html

# Automatically determine the number of colors needed
num_levels <- length(unique(census_data$Region))
num_levels
[1] 10

The num_levels variable is a dynamic way to determine the number of unique levels in a categorical variable, such as Region. This approach is particularly helpful when you don’t know in advance how many categories exist in the dataset.

The code above calculates the number of unique categories in the Region variable, ensuring that your plot’s color palette matches the data’s requirements. Based on the value of num_levels, you can choose an appropriate color palette from libraries like RColorBrewer. For example:

library(RColorBrewer)
# Use an appropriate Brewer palette based on the number of levels
palette <- if (num_levels <= 8) "Set2" else "Paired" # Choose a palette with enough colors

This dynamically selects a palette suitable for the number of categories. If there are 8 or fewer levels, the Set2 palette is used; for more levels, Paired ensures enough distinct colors (there’s several palettes, check the link above for more).

When applying the palette in ggplot2, the function scale_color_brewer(palette = palette) ensures that the plot assigns colors based on the selected scheme. This process avoids hardcoding colors or palettes and ensures the plot adapts to changes in the data, such as when categories are added or removed.

In this plot we also change the x-axis. Residents ranges from about 2,000 (Isles of Scilly) to over 1.1 million (Birmingham), so in the first scatterplot most districts were squeezed on the left. On a log scale each step of the axis multiplies the value by 10, which spreads the districts out. label_comma() writes 100000 as 100,000.

ggplot(census_data, aes(x = Residents, y = mean_age, color = factor(Region))) +
 geom_point(size = 3) +
 scale_color_brewer(palette = palette) + # Dynamically chosen palette
 scale_x_log10(labels = scales::label_comma()) + # Log scale for a very skewed variable
 labs(title = " Write a title")

NoteQuestion

Paired builds its colours in pairs (light and dark of the same hue), so two regions that happen to be next to each other in the legend look related even though they are not. More generally, ten colours on one scatterplot are hard to tell apart with any palette. What would you do instead? (Hint: look back at faceting, or colour only the region you want to talk about and leave the others grey.)

You can also create your own palette of colours.

ggplot(census_data, aes(x = Residents, y = mean_age, color = factor(Region))) +
 geom_point(size = 3) +
 scale_color_manual(values = c("red", "blue", "green", "purple", "orange", "pink", "brown", "yellow", "gray", "skyblue")) +
 scale_x_log10(labels = scales::label_comma()) +
 labs(
  title = "Scatterplot of Residents vs Mean Age by Region",
  x = "Residents (log scale)",
  y = "Mean Age",
  color = "Region"
 ) +
 theme_minimal()

NoteQuestion

This palette is a bad example on purpose. Which colours are hard to tell apart? Which one almost disappears on a white background? Would a colour-blind reader (about 1 in 12 men) manage to read it? When you pick colours by hand, start from a ColorBrewer or viridis palette instead of colour names.

Category Function Description Example Usage
Discrete Color Scales scale_color_brewer() Use pre-defined discrete palettes from RColorBrewer. scale_color_brewer(palette = "Set1")
scale_fill_brewer() Fill colors for discrete variables from RColorBrewer. scale_fill_brewer(palette = "Pastel2")
scale_color_manual() Manually assign colors for discrete variables. scale_color_manual(values = c("red", "blue", "green"))
scale_fill_manual() Manually assign fill colors for discrete variables. scale_fill_manual(values = c("purple", "orange", "yellow"))
scale_color_viridis_d() Use discrete palettes from the viridis package (colorblind-friendly). scale_color_viridis_d(option = "plasma")
scale_fill_viridis_d() Fill discrete variables with viridis palettes. scale_fill_viridis_d(option = "cividis")
Continuous Color Scales scale_color_gradient() Two-color gradient for continuous variables. scale_color_gradient(low = "blue", high = "red")
scale_fill_gradient() Two-color gradient for continuous fill variables. scale_fill_gradient(low = "green", high = "yellow")
scale_color_gradient2() Diverging gradient with a midpoint for continuous variables. scale_color_gradient2(low = "blue", mid = "white", high = "red", midpoint = 0)
scale_fill_gradient2() Diverging gradient with a midpoint for continuous fill variables. scale_fill_gradient2(low = "purple", mid = "gray", high = "orange", midpoint = 50)
scale_color_gradientn() Multi-color gradient for continuous variables. scale_color_gradientn(colors = c("blue", "green", "yellow", "red"))
scale_fill_gradientn() Multi-color gradient for continuous fill variables. scale_fill_gradientn(colors = c("lightblue", "white", "pink"))
scale_color_viridis_c() Continuous color scales from viridis. scale_color_viridis_c(option = "magma")
scale_fill_viridis_c() Continuous fill scales from viridis. scale_fill_viridis_c(option = "inferno")
Axis Scales scale_x_continuous() Customize numeric X-axis with breaks and labels. scale_x_continuous(breaks = seq(0, 100, 10))
scale_y_continuous() Customize numeric Y-axis with breaks and labels. scale_y_continuous(labels = scales::percent_format())
scale_x_log10() Logarithmic transformation for X-axis. scale_x_log10()
scale_y_log10() Logarithmic transformation for Y-axis. scale_y_log10()
scale_x_reverse() Reverse the X-axis direction. scale_x_reverse()
scale_y_reverse() Reverse the Y-axis direction. scale_y_reverse()
Zooming coord_cartesian() Zoom into part of the plot without removing data (see Part 3). coord_cartesian(ylim = c(0, 500000))
Shape and Size Scales scale_shape_manual() Manually assign shapes to categories for points. scale_shape_manual(values = c(19, 17, 15))
scale_size_continuous() Scale the size of points based on a continuous variable. scale_size_continuous(range = c(1, 10))
scale_size_manual() Manually specify point sizes for categorical variables. scale_size_manual(values = c(2, 4, 6))

6.1.7 Additional Functions for Customization

  • labs(): Adds labels for axes, title, legend, and a caption (e.g. for the data source).
  • coord_flip(): Flips X and Y axes for horizontal plots.

Labeling (this chunk only shows the syntax: add these lines to a plot with +):

# labels
labs(
 title = "Plot Title",
 x = "X-Axis Label",
 y = "Y-Axis Label",
 color = "Legend Title",
 caption = "Source: ..."
)

Flipping:

# flipping
ggplot(census_data, aes(x = factor(Region), y = Residents)) +
 geom_boxplot() +
 coord_flip() +
 labs(title = "Horizontal Boxplot")

Key Tips for ggplot2:

  • Start with simple plots and incrementally add layers (+).
  • Use themes (theme_minimal(), theme_classic()) to clean up your plots.
  • Explore palettes with RColorBrewer or viridis for colorblind-friendly options.

6.2 Part 2 - Visualisation: Making decent graphs (1h)

This section demonstrates how to create publication-quality visualisations in R using ggplot2.

Learning goals Developing an understanding of, and ability to create academic standard data visualisations.

The green Task boxes are short exercises: do them as you go, they take a few minutes each. Examples marked (Optional) are extra: skip them if you are short of time, and come back to them when you need that type of chart for your assignment.

Let’s load the datasets first.

library(tidyverse) # dplyr, tidyr and forcats (we used fct_relevel in Lab 03)
Warning: package 'tidyverse' was built under R version 4.5.2
Warning: package 'tibble' was built under R version 4.5.1
Warning: package 'tidyr' was built under R version 4.5.1
Warning: package 'readr' was built under R version 4.5.1
Warning: package 'purrr' was built under R version 4.5.1
Warning: package 'dplyr' was built under R version 4.5.1
Warning: package 'forcats' was built under R version 4.5.1
Warning: package 'lubridate' was built under R version 4.5.1
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.1.4     ✔ readr     2.1.5
✔ forcats   1.0.0     ✔ stringr   1.5.2
✔ lubridate 1.9.4     ✔ tibble    3.3.0
✔ purrr     1.1.0     ✔ tidyr     1.3.1
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
frs_data <- read.csv("../data/FRS/FRS16-17_labels.csv")
census_data <- read.csv("../data/Census2021/EW_DistrictPercentages.csv")

Preparing the FRS. Three things to fix before plotting, all of which you have met in Lab 03:

  1. R stores categories as text and sorts them alphabetically: health would come out as Bad, Fair, Good, Not known, Very Bad, Very Good. For an ordinal variable we want the natural order, so we set it with fct_relevel().
  2. highest_qual includes Dependent child (children are not asked about qualifications) and both health and highest_qual include Not known. These are not categories we want to compare, so we keep adults with known answers.
  3. Variables such as hh_income_gross and hh_size describe the household, but the FRS has one row per person. If we plot them for every person, each household is counted once per member (a couple appears once among men and once among women, with the same income). For household variables we keep one row per household: the household reference person (HRP), as we did in Lab 03.
frs_data <- frs_data %>%
 mutate(
  health = fct_relevel(health, "Very Good", "Good", "Fair", "Bad", "Very Bad"), # "Not known" goes last
  highest_qual = fct_relevel(highest_qual, "Degree or above", "A-level or equivalent",
                             "GCSE or equivalent", "Other") # "Dependent child" and "Not known" go last
 )

# Adults with known health and qualification (one row per person)
frs_adults <- frs_data %>%
 filter(dependent == "Independent",
        health != "Not known",
        !highest_qual %in% c("Not known", "Dependent child")) %>%
 droplevels() # drop the categories we filtered out

# One row per household: the household reference person
frs_hh <- frs_adults %>%
 filter(hrp == "HRP")

levels(frs_adults$health)
[1] "Very Good" "Good"      "Fair"      "Bad"       "Very Bad" 
levels(frs_adults$highest_qual)
[1] "Degree or above"       "A-level or equivalent" "GCSE or equivalent"   
[4] "Other"                

6.2.1 Distribution of 1 Numerical variable:

Histogram

ggplot(census_data, aes(x = pct_Age_20_to_29)) +
 geom_histogram(bins = 5, fill = "steelblue", color = "black") +
 labs(
  title = "Share of residents aged 20 to 29, districts of England and Wales (2021)",
  x = "Residents aged 20 to 29 (%)",
  y = "Number of districts"
 ) +
 theme_minimal()

The bins parameter in a histogram determines the number of intervals (bins) into which the data range is divided. Each bin represents a range of values along the x-axis, and the height of each bar shows the count of observations within that range. For example, if bins = 5, the data is divided into five equal-width intervals. Using fewer bins results in a coarser view of the data, while more bins provide a finer, more detailed representation. However, too many bins can make the histogram appear cluttered and difficult to interpret. The width of each bin is automatically calculated by dividing the range of the data by the number of bins.

TipTask

Five bins hide the shape of this distribution. Try bins = 15 and bins = 40. What happens to the right-hand side of the distribution? Which districts do you think are out there? (Check with census_data %>% arrange(desc(pct_Age_20_to_29)) %>% select(District, pct_Age_20_to_29) %>% head().)

Density Plot (Optional)

ggplot(census_data, aes(x = Residents)) +
 geom_density(fill = "lightblue", alpha = 0.7) +
 scale_x_continuous(labels = scales::label_comma()) +
 labs(
  title = "Residents per district, England and Wales (2021)",
  x = "Residents",
  y = "Density"
 ) +
 theme_minimal()

Note the long right tail: a handful of very large districts (Birmingham, Leeds, Cornwall…). We will come back to them with the boxplot.

Histogram + Density Distribution (Optional)

# Plot histogram with density overlay for a chosen variable (e.g., 'pct_No_qualifications')
ggplot(census_data, aes(x = pct_No_qualifications)) +
 geom_histogram(aes(y = after_stat(density)), bins = 20, color = "black", fill = "skyblue", alpha = 0.7) +
 geom_density(color = "darkblue", linewidth = 1) +
 labs(
  title = "Residents with no qualifications, districts of England and Wales (2021)",
  x = "Residents aged 16+ with no qualifications (%)",
  y = "Density"
 ) +
 theme_minimal()

Box Plot

A box plot, also known as a box-and-whisker plot, is a graphical representation of the distribution of a dataset. The central box goes from the first quartile (Q1) to the third quartile (Q3), so it contains the middle 50% of the observations (the interquartile range, IQR), and the line inside it is the median (Q2). In ggplot2 the whiskers extend to the most extreme values that are still within 1.5 × IQR of the box, so they are not necessarily the minimum and the maximum. Observations beyond the whiskers are drawn as individual points and are usually called outliers.

The box plot provides a concise summary of the data distribution, highlighting the spread, center, and potential skewness.

library(scales) # For label_comma()
Warning: package 'scales' was built under R version 4.5.1

Attaching package: 'scales'
The following object is masked from 'package:purrr':

    discard
The following object is masked from 'package:readr':

    col_factor
ggplot(census_data, aes(x = "", y = Residents)) + # x = "" because there is only one group
 geom_boxplot(fill = "lightgreen", color = "black") +
 labs(title = "Residents per district, England and Wales (2021)", x = NULL, y = "Residents") +
 theme_minimal() +
 scale_y_continuous(labels = label_comma()) # comma-separated format for large numbers

For a single variable, a histogram or a density plot usually tells you more, because it shows the shape of the distribution (for example, two peaks), which a box plot hides. Box plots are most useful when you compare distributions across groups, as we do below.

Notice the outliers. Outliers are data points that deviate significantly from the overall pattern of a dataset. They can arise due to measurement errors, variability in the data, or the presence of extreme values. Outliers can heavily influence statistical analyses, such as means or regression models, potentially leading to misleading conclusions. Boxplots allow spotting them, along with interquartile range (IQR) analysis. Remember, though, that a point beyond the whiskers is not necessarily an error: Birmingham really does have over a million residents. Look at your outliers and understand them, rather than dropping them because they are outliers.

6.2.1.1 Zooming without distorting

Most of the plot above is taken up by a few very large districts. You may be tempted to cut the axis at 500,000 with scale_y_continuous(limits = c(0, 500000)). Don’t: limits set inside a scale_ function remove every observation outside the range before the box plot is computed. Here 9 districts would silently disappear (Birmingham, Leeds, Manchester, Sheffield, Bradford, Cornwall, County Durham, Wiltshire and Buckinghamshire), the box itself would change, and R would only tell you in a warning.

There are two honest alternatives. coord_cartesian() zooms in like a magnifying glass: all the data are still used to compute the box, only the view changes.

ggplot(census_data, aes(x = "", y = Residents)) +
 geom_boxplot(fill = "lightgreen", color = "black") +
 coord_cartesian(ylim = c(0, 500000)) + # zoom: no data removed
 scale_y_continuous(labels = label_comma()) +
 labs(title = "Residents per district, England and Wales (2021)",
      subtitle = "Zoomed to 0 to 500,000: 9 larger districts are outside the view",
      x = NULL, y = "Residents") +
 theme_minimal()

For very skewed variables like this one, a log scale is often the better choice, because it shows all districts at once.

ggplot(census_data, aes(x = "", y = Residents)) +
 geom_boxplot(fill = "lightgreen", color = "black") +
 scale_y_log10(labels = label_comma()) +
 labs(title = "Residents per district, England and Wales (2021)", x = NULL, y = "Residents (log scale)") +
 theme_minimal()

TipTask

Copy the first box plot and add scale_y_continuous(limits = c(0, 500000)). Read the warning in the console: how many rows were removed? Compare the median line with the coord_cartesian() version. Which of the two would you trust in a report?

6.2.2 Distribution of 1 Categorical variable:

Bar Chart

Because we set the order of highest_qual above, the bars follow the qualification ladder instead of the alphabet.

ggplot(frs_adults, aes(x = highest_qual)) +
 geom_bar(fill = "skyblue", color = "black") +
 scale_y_continuous(labels = label_comma()) +
 labs(title = "Highest educational qualification, adults in the FRS 2016-17",
      x = "Highest Educational Qualification", y = "Number of adults") +
 theme_minimal()

Horizontal Bar Chart: with long category labels, add + coord_flip() to the chart above to turn the bars horizontally.

6.2.3 Comparing variables

1 numerical, 1 categorical: Boxplot

Household income is a household variable, so we use frs_hh (one row per household) and the qualification of the household reference person. Incomes have a very long right tail, so we zoom with coord_cartesian(): every household is still used to compute the boxes.

ggplot(frs_hh, aes(x = highest_qual, y = hh_income_gross, fill = highest_qual)) +
 geom_boxplot() +
 coord_cartesian(ylim = c(0, 150000)) + # zoom, no data removed
 scale_y_continuous(labels = label_comma()) +
 scale_fill_brewer(palette = "Set2") +
 labs(
  title = "Household income by highest qualification",
  subtitle = "Household reference persons, FRS 2016-17",
  x = "Highest Educational Qualification",
  y = "Gross household income (£ per year)"
 ) +
 theme_minimal() +
 theme(legend.position = "none") # the x-axis already tells us which box is which

1 numerical, 1 categorical: Density Ridges (Optional)

Density ridges need a numerical variable that can take many values. A variable such as hh_size (1, 2, 3, … people) would produce waves between whole numbers that do not exist in the data, so we use income again.

library(ggridges) # need a library for this
Warning: package 'ggridges' was built under R version 4.5.3
ggplot(frs_hh, aes(x = hh_income_gross, y = highest_qual, fill = highest_qual)) +
 geom_density_ridges(alpha = 0.7) +
 coord_cartesian(xlim = c(0, 150000)) +
 scale_x_continuous(labels = label_comma()) +
 scale_fill_brewer(palette = "Set2") +
 labs(
  title = "Household income by highest qualification",
  subtitle = "Household reference persons, FRS 2016-17",
  x = "Gross household income (£ per year)",
  y = "Highest Qualification"
 ) +
 theme_minimal() +
 theme(legend.position = "none")
Picking joint bandwidth of 3830

2 Categorical Variables: Stacked Bar Chart

Health is ordinal, so we use a sequential palette (light to dark) in the same order as the categories. Note the adjustments made for making the labels look better.

ggplot(frs_adults, aes(x = highest_qual, fill = health)) +
 geom_bar(position = "stack") +
 scale_fill_brewer(palette = "Blues") +
 scale_y_continuous(labels = label_comma()) +
 labs(
  title = "Health Status by Highest Qualification, adults in the FRS 2016-17",
  x = "Highest Qualification",
  y = "Count of Individuals",
  fill = "Health Status"
 ) +
 theme_minimal() +
 theme(
  axis.text.x = element_text(angle = 45, hjust = 1), # Rotate X-axis labels for readability
  legend.title = element_text(size = 12),      # Adjust legend title size
  legend.text = element_text(size = 10)       # Adjust legend text size
 )

Side-by-Side Bar Chart (Two-Way Frequency Distribution) (Optional)

This type of chart can get messy: it works when you need to compare each health category across qualification groups, but with five health categories it is already crowded.

ggplot(frs_adults, aes(x = highest_qual, fill = health)) +
 geom_bar(position = "dodge") +
 scale_fill_brewer(palette = "Blues") +
 scale_y_continuous(labels = label_comma()) +
 labs(
  title = "Health Status by Highest Qualification, adults in the FRS 2016-17",
  x = "Highest Qualification",
  y = "Count of Individuals",
  fill = "Health Status"
 ) +
 theme_minimal() +
 theme(
  axis.text.x = element_text(angle = 45, hjust = 1),
  legend.title = element_text(size = 12),
  legend.text = element_text(size = 10)
 )

2 Categorical Variable counts to percentages: Stacked Percentage Graph

The two charts above show counts, so the groups with more people (e.g. GCSE) dominate. To compare how health is distributed within each qualification group, we convert counts to percentages.

A cross tabulation (or contingency table) is a statistical tool used to analyze the relationship between two or more categorical variables. It organizes data into a table format where: - Rows represent the categories of one variable. - Columns represent the categories of another variable. - Cells display the counts or frequencies of data points that fall into each combination of the row and column categories.

# Create a cross-tabulation of observed counts
cross_tab <- table(frs_adults$health, frs_adults$highest_qual)
cross_tab
           
            Degree or above A-level or equivalent GCSE or equivalent Other
  Very Good            2854                  1348               2061   450
  Good                 2953                  1625               3056   853
  Fair                 1097                   868               1784   696
  Bad                   262                   200                524   231
  Very Bad               67                    55                133    64
# Convert the cross-tabulation to a data frame (one row per combination)
cross_tab_df <- as.data.frame(cross_tab)
colnames(cross_tab_df) <- c("Health", "Qualification", "Count")

The data is reshaped into a data frame for compatibility with ggplot2. The column Count still contains counts: position = "fill" is what turns them into proportions, by stretching every bar to 100%. Each bar is one qualification group, so the chart shows the percentage of each group in each health category (the column percentages of the cross tabulation).

# Create a stacked percentage bar chart
ggplot(cross_tab_df, aes(x = Qualification, y = Count, fill = Health)) +
 geom_col(position = "fill") +
 scale_fill_brewer(palette = "Blues") +
 scale_y_continuous(labels = scales::percent_format()) +
 labs(
  title = "Health by Highest Qualification (Percentage)",
  x = "Highest Qualification",
  y = "Percentage",
  fill = "Health Status"
 ) +
 theme_minimal() +
 theme(axis.text.x = element_text(angle = 45, hjust = 1))

NoteQuestion

Which variable goes on the x-axis matters. Here each bar is a qualification group, so the chart answers: how is health distributed among people with a given qualification? Swap x = Health and fill = Qualification: what question does the new chart answer? If your research question is “is education associated with health?”, which version is the right one?

3+ Numerical Variables: Boxplot

To compare three or more numerical variables using boxplots in ggplot2, one needs to reshape the data to a long format so that each numerical variable is treated as a category in a single column. Boxplots on the same axis only make sense if the variables share the same unit: here they are all percentages of residents aged 16+, and together they describe the qualification profile of districts.

Here’s how you can do it, using tidyverse

# Reshape the data into long format
long_data <- census_data %>%
 pivot_longer(
  cols = c(pct_No_qualifications, pct_GCSE, pct_A_level, pct_Degree_plus),
  names_to = "Variable",
  values_to = "Value"
 ) %>%
 mutate(Variable = factor(Variable,
                          levels = c("pct_No_qualifications", "pct_GCSE", "pct_A_level", "pct_Degree_plus"),
                          labels = c("No qualifications", "GCSE", "A level", "Degree or above")))

The code above reshapes the data from a wide format to a long format using the pivot_longer() function from the tidyverse package. In the original dataset, each column represents a separate variable (e.g., pct_No_qualifications, pct_GCSE, ..), and their values are stored in individual columns. The transformation collapses these columns into two new columns: one for the variable names (Variable) and another for their corresponding values (Value). This format is useful for plotting or analysis where variables are treated uniformly, such as when creating boxplots or facet grids in ggplot2. The last step, factor(..., levels, labels), sets the order of the boxes and gives them readable names.

# Create the boxplot
ggplot(long_data, aes(x = Variable, y = Value, fill = Variable)) +
 geom_boxplot() +
 scale_fill_brewer(palette = "Blues") +
 labs(
  title = "Highest qualification of residents aged 16+, by district",
  subtitle = "England and Wales, Census 2021",
  x = "Highest qualification",
  y = "Residents aged 16+ (%)"
 ) +
 theme_minimal() +
 theme(legend.position = "none")

6.2.4 Visualising Relationships:

2 Numerical Variables: Scatterplot

ggplot(census_data, aes(x = pct_No_qualifications, y = pct_Very_bad_health, color = factor(Country))) +
 geom_point(size = 3, alpha = 0.7) +
 scale_color_brewer(palette = "Dark2") +
 labs(
  title = "No qualifications and very bad health, districts of England and Wales (2021)",
  x = "Residents with no qualifications (%)",
  y = "Residents in very bad health (%)",
  color = "Country"
 ) +
 theme_minimal()

WarningDistricts are not people

Each point is a district. The plot shows that districts with more residents without qualifications also have more residents in very bad health. It does not tell us that people without qualifications are in worse health: that would be an ecological fallacy, drawing conclusions about individuals from data about areas. To look at individuals, you need individual data such as the FRS.

2 Numerical Variables + 1 Categorical: Scatterplot

ggplot(census_data, aes(x = pct_No_qualifications, y = pct_Very_bad_health, color = factor(Region))) +
 geom_point(size = 3, alpha = 0.7) +
 labs(
  title = "No qualifications and very bad health by Region, England and Wales (2021)",
  x = "Residents with no qualifications (%)",
  y = "Residents in very bad health (%)",
  color = "Region"
 ) +
 theme_minimal()

TipTask

Ten colours are too many to read. Rewrite this plot with facet_wrap(~ Region) instead of colour. Which version helps you see regional differences?

3+ Numerical Variables: Correlogram

A correlogram is a visual representation of a correlation matrix, where the strength and direction of relationships between numerical variables are displayed. The matrix is typically a grid, with variables listed along both the rows and columns. Each cell in the matrix shows the correlation coefficient between two variables.

The library corrplot would do it for us. Check: https://cran.r-project.org/web/packages/corrplot/vignettes/corrplot-intro.html for deeper customisation.

In the corrplot package, a correlogram can use colors, shapes, or numbers to represent the correlation. For example, colors ranging from blue to red often signify negative to positive correlations, while white may indicate no correlation (a diverging palette, because correlations have a meaningful midpoint at 0). Similarly, circles or other shapes can vary in size to depict the strength of the relationship. The corrplot function simplifies creating correlograms with customizable options. For example, using method = “number” places correlation coefficients in each cell, while method = “circle” represents correlations graphically.

Correlograms are valuable for quickly identifying patterns or strong relationships between variables, such as spotting which features might influence one another in a dataset. Here we use the variables of the regression model you fitted in Lab 03 (and that we turn into a table in Part 4): a correlogram is a quick check before fitting a model.

library(corrplot)
Warning: package 'corrplot' was built under R version 4.5.1
corrplot 0.95 loaded
# Select the necessary variables from the dataset
selected_vars <- census_data[, c("pct_Very_bad_health", "pct_No_qualifications", "pct_Males", "pct_Higher_manager_prof")]

# Calculate the correlation matrix
cor_matrix <- cor(selected_vars, use = "complete.obs")

# Generate the correlation plot
corrplot(cor_matrix,
     method = "number", # Display numbers
     col = colorRampPalette(c("blue", "white", "red"))(200), # Color gradient
     tl.col = "black", # Text color for labels
     tl.srt = 45,    # Rotate text labels
     title = "Correlation Matrix of Selected Variables",
     mar = c(0, 0, 1, 0)) # Adjust margins

(Optional) We can also include circles to graphically represent correlations.

# Generate the correlation plot with circles
corrplot(cor_matrix,
     method = "circle", # Display circles
     col = colorRampPalette(c("blue", "white", "red"))(200), # Color gradient
     tl.col = "black", # Text color for labels
     tl.srt = 45,    # Rotate text labels
     title = "Correlation Matrix of Selected Variables",
     mar = c(0, 0, 1, 0)) # Adjust margins

3+ Numerical Variables: Scatterplot matrix

A scatterplot matrix shows a scatterplot for every pair of variables. Base R does it in one line with pairs():

pairs(selected_vars,
      col = alpha("steelblue", 0.5), pch = 16,
      main = "Scatterplot Matrix of Selected Variables")

And you can colour the points by a categorical variable, for example Country:

country_colours <- c(England = "#1b9e77", Wales = "#d95f02")

pairs(selected_vars,
      col = country_colours[census_data$Country], pch = 16,
      main = "Scatterplot Matrix by Country (green = England, orange = Wales)")

If you want the ggplot2 look, you need to build a long table with one row per pair of variables and per district.

# Create pairwise combinations of variable names.
# stringsAsFactors = FALSE keeps the names as text, so selected_vars[[Variable1]]
# picks the column by its name (with a factor, R would use its position instead).
scatter_data <- expand.grid(
 Variable1 = names(selected_vars),
 Variable2 = names(selected_vars),
 stringsAsFactors = FALSE
)

# Add the data values for the pairs
scatter_data <- scatter_data %>%
 rowwise() %>%
 mutate(
  Value1 = list(selected_vars[[Variable1]]), # Extract values for Variable1
  Value2 = list(selected_vars[[Variable2]]), # Extract values for Variable2
  Country = list(census_data$Country)        # Include 'Country' in the data
 ) %>%
 unnest(c(Value1, Value2, Country)) # Unnest the lists into rows

ggplot(scatter_data, aes(x = Value2, y = Value1, fill = Country)) + # x = column variable, y = row variable
 geom_point(alpha = 0.6, shape = 21, size = 2) + # shape 21 has a fill
 facet_grid(Variable1 ~ Variable2, scales = "free") +
 scale_fill_brewer(palette = "Dark2") +
 labs(title = "Scatterplot Matrix with Fill by Country", x = "", y = "", fill = "Country") +
 theme_minimal()

expand.grid() generates all possible combinations of the variable names, one row per pair. mutate() then attaches the actual values of each pair to two new columns, Value1 and Value2 (as lists), and unnest() turns the lists into rows. Finally facet_grid(Variable1 ~ Variable2) draws one scatterplot per pair: the row variable goes on the y-axis and the column variable on the x-axis, as in pairs(), so that panels in the same column share the same x-axis.

1 Numerical Variable, 2+ Categorical Variables: Boxplot faceting

Household income again, so one row per household (frs_hh): marital status and sex are those of the household reference person.

ggplot(frs_hh, aes(x = marital_status, y = hh_income_gross, fill = marital_status)) +
 geom_boxplot() +
 facet_wrap(~ sex) +
 coord_cartesian(ylim = c(0, 100000)) + # zoom only: all households are used to compute the boxes
 scale_y_continuous(labels = label_comma()) +
 scale_fill_brewer(palette = "Set2") +
 labs(
  title = "Household income by marital status and sex",
  subtitle = "Household reference persons, FRS 2016-17",
  x = "Marital Status",
  y = "Gross household income (£ per year)"
 ) + # Removed 'fill' label to avoid legend creation
 theme_minimal() +
 theme(
  axis.text.x = element_text(angle = 45, hjust = 1), # Rotate x-axis labels for readability
  legend.position = "none" # the x-axis already tells us which box is which
 )

1 Numerical Variable, 2+ Categorical Variables: Violin Plot faceting (Optional)

A violin plot combines aspects of a box plot and a density plot. It displays the distribution of a continuous variable, showing its probability density across different levels of a categorical variable. The plot consists of a vertical axis representing the variable of interest and horizontal axes that group data by categorical variables. The shape of the “violin” represents the distribution’s density, often mirrored on both sides, making it easier to see the spread and skewness of the data.

ggplot(frs_hh, aes(x = marital_status, y = hh_income_gross, fill = marital_status)) +
 geom_violin() +
 facet_wrap(~ sex) +
 coord_cartesian(ylim = c(0, 100000)) +
 scale_y_continuous(labels = label_comma()) +
 scale_fill_brewer(palette = "Set2") +
 labs(
  title = "Household income by marital status and sex",
  subtitle = "Household reference persons, FRS 2016-17",
  x = "Marital Status",
  y = "Gross household income (£ per year)"
 ) +
 theme_minimal() +
 theme(
  axis.text.x = element_text(angle = 45, hjust = 1),
  legend.position = "none"
 )

6.3 Part 3: Publication-Ready Tables

We will be using kableExtra to create nicely formatted tables for a series of outputs in RStudio:

library(kableExtra)
Warning: package 'kableExtra' was built under R version 4.5.1

Attaching package: 'kableExtra'
The following object is masked from 'package:dplyr':

    group_rows

6.3.1 Summarising datasets

Only for summarising statistics we use vtable that makes use of kableExtra behind the scenes. You can use the function st() or sumtable(), they do the same thing. See https://cran.r-project.org/web/packages/vtable/vignettes/sumtable.html

library(vtable)
Warning: package 'vtable' was built under R version 4.5.3
# Generate the summary table
st(census_data, vars = c("pct_Very_bad_health", "pct_No_qualifications", "pct_Males", "pct_Higher_manager_prof"), out = 'kable')
Summary Statistics
Variable N Mean Std. Dev. Min Pctl. 25 Pctl. 75 Max
pct_Very_bad_health 331 1.2 0.34 0.55 0.92 1.4 2.4
pct_No_qualifications 331 18 4 6.6 15 20 29
pct_Males 331 49 0.66 47 49 49 55
pct_Higher_manager_prof 331 13 4.7 5.5 9.8 16 40

6.3.2 Creating a Well-Formatted Table from a Cross Tabulation

We can also convert a cross tabulation to a nice table. A report table usually shows percentages rather than counts, in the same wide shape as the cross tabulation: health in the rows, qualification in the columns.

# cross tabulation (counts), as above
cross_tab <- table(frs_adults$health, frs_adults$highest_qual)

# Column percentages: each column (qualification group) sums to 100
cross_tab_pct <- round(100 * prop.table(cross_tab, margin = 2), 1)
cross_tab_pct
           
            Degree or above A-level or equivalent GCSE or equivalent Other
  Very Good            39.5                  32.9               27.3  19.6
  Good                 40.8                  39.7               40.4  37.2
  Fair                 15.2                  21.2               23.6  30.3
  Bad                   3.6                   4.9                6.9  10.1
  Very Bad              0.9                   1.3                1.8   2.8
as.data.frame.matrix(cross_tab_pct) %>%
 rownames_to_column("Health") %>%
 kbl(caption = "Health by highest educational qualification, adults in the FRS 2016-17 (column %)") %>%
 kable_styling(full_width = FALSE, position = "left") %>%
 add_header_above(c(" " = 1, "Highest Educational Qualification" = ncol(cross_tab_pct)))
Health by highest educational qualification, adults in the FRS 2016-17 (column %)
Highest Educational Qualification
Health Degree or above A-level or equivalent GCSE or equivalent Other
Very Good 39.5 32.9 27.3 19.6
Good 40.8 39.7 40.4 37.2
Fair 15.2 21.2 23.6 30.3
Bad 3.6 4.9 6.9 10.1
Very Bad 0.9 1.3 1.8 2.8
  • Column percentages: prop.table(cross_tab, margin = 2) divides each cell by its column total, so each column sums to 1 (100 after multiplying by 100). These are the same numbers shown in the stacked percentage chart above. With margin = 1 you would get row percentages instead (each health category summing to 100).
  • Back to a data frame: as.data.frame.matrix() keeps the wide shape of the table (unlike as.data.frame(), which gives one row per combination), and rownames_to_column("Health") turns the health categories into a proper first column.
  • Generate a Table with kable: kbl(caption = ...) uses the kbl function from the kableExtra package to create a basic, well-formatted table. The caption argument adds a title to the table.
  • Style the Table: %>% kable_styling(full_width = FALSE, position = "left"). This enhances the appearance of the table with the kable_styling function. full_width = FALSE ensures the table is not stretched to the full width of the document or webpage; position = "left": Aligns the table to the left side of the page.
  • Add a Header Row: %>% add_header_above(c(" " = 1, "Highest Educational Qualification" = ncol(cross_tab_pct))) adds an additional header row above the table: the first column (“Health”) has a blank header in this new row, and all the qualification columns are grouped under the label “Highest Educational Qualification”.

6.3.3 Creating a Well-Formatted Table from a Regression Model

Finally, we can derive a table to show the Multiple Linear Regression results. This is the model you fitted in Lab 03.

# Load required libraries
library(broom)
Warning: package 'broom' was built under R version 4.5.1
# Fit the regression model
model <- lm(pct_Very_bad_health ~ pct_No_qualifications + pct_Males + pct_Higher_manager_prof,
      data = census_data)

summary(model) is what you read in the console, but it is not a table for a report: never paste it (or a screenshot of the console) into your assignment. It is full of things the reader doesn’t need (the call, residual quantiles, significance stars and codes), the variable names are R names, and it has no caption or source.

summary(model)

Call:
lm(formula = pct_Very_bad_health ~ pct_No_qualifications + pct_Males + 
    pct_Higher_manager_prof, data = census_data)

Residuals:
     Min       1Q   Median       3Q      Max 
-0.49109 -0.13567 -0.03678  0.09850  0.76687 

Coefficients:
                         Estimate Std. Error t value Pr(>|t|)    
(Intercept)              4.002933   0.879809   4.550 7.58e-06 ***
pct_No_qualifications    0.052826   0.005911   8.937  < 2e-16 ***
pct_Males               -0.073535   0.017845  -4.121 4.79e-05 ***
pct_Higher_manager_prof -0.013183   0.004938  -2.670  0.00797 ** 
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.2133 on 327 degrees of freedom
Multiple R-squared:  0.6102,    Adjusted R-squared:  0.6066 
F-statistic: 170.6 on 3 and 327 DF,  p-value: < 2.2e-16

Let’s tidy up the regression output instead. tidy() turns the coefficients into a data frame; we then give the predictors readable names (the reader doesn’t know what pct_Higher_manager_prof is) and format the p-values. Very small p-values would be rounded to 0.000, which is not a real value: label_pvalue() writes them as “<0.001”, the usual convention in reports.

regression_table <- tidy(model) %>%
 mutate(
  term = recode(term,
                "(Intercept)" = "Intercept",
                pct_No_qualifications = "No qualifications (%)",
                pct_Males = "Males (%)",
                pct_Higher_manager_prof = "Higher managerial and professional (%)"),
  p.value = label_pvalue()(p.value) # e.g. "<0.001" instead of 0.000
 ) %>%
 select(term, estimate, std.error, statistic, p.value) %>%
 rename(
  Term = term,
  Estimate = estimate,
  `Std. Error` = std.error,
  `t value` = statistic,
  `P value` = p.value
 )

Create and style the regression table

regression_table %>%
 kbl(
  caption = "Table 1. OLS regression of the percentage of residents in very bad health, districts of England and Wales (2021)",
  digits = 3,
  col.names = c("Predictor", "Estimate", "Std. Error", "t Value", "P Value")
 ) %>%
 kable_styling(full_width = FALSE, bootstrap_options = c("striped", "hover", "condensed")) %>%
 column_spec(2:5, width = "3cm") %>% # Adjust column widths
 add_header_above(c(" " = 1, "Coefficients" = 4)) %>% # Add grouped header
 footnote(general = paste0("n = ", nobs(model), " districts; R² = ", round(summary(model)$r.squared, 2),
                           ". Source: Census 2021 (ONS)."),
          general_title = "")
Table 1. OLS regression of the percentage of residents in very bad health, districts of England and Wales (2021)
Coefficients
Predictor Estimate Std. Error t Value P Value
Intercept 4.003 0.880 4.550 <0.001
No qualifications (%) 0.053 0.006 8.937 <0.001
Males (%) -0.074 0.018 -4.121 <0.001
Higher managerial and professional (%) -0.013 0.005 -2.670 0.008
n = 331 districts; R² = 0.61. Source: Census 2021 (ONS).
  • kable_styling() This function customizes the appearance of a kable table. The arguments used are:

    • full_width = FALSE: Ensures the table is not stretched to fill the entire width of the page.

    • bootstrap_options = c("striped", "hover", "condensed"):

      • striped: Adds alternating row colors for better readability.

      • hover: Highlights rows when hovered over with the mouse (for HTML tables).

      • condensed: Reduces the table’s vertical spacing, making it more compact.

  • column_spec(2:5, width = "3cm"). This function customizes specific columns of the table.

    • 2:5: Targets columns 2 through 5 for styling.

    • width = "3cm": Sets the width of these columns to 3 cm, ensuring uniform and readable column sizes.

  • caption: a numbered, descriptive title (“Table 1. …”), so that you can refer to it in the text.

  • add_header_above(c(" " = 1, "Coefficients" = 4)). This function adds an additional header row above the table. This is used to customize the header of a table.

    • " " = 1 Leaves the first column (e.g., the Term column) without a header, spanning 1 column.
    • "Coefficients" = 4: columns 2, 3, 4, and 5 are grouped together under one header, labelled “Coefficients” (4 is the number of columns it spans).
  • footnote(general = ...): a note under the table with the number of observations, the R² and the data source. nobs(model) and summary(model)$r.squared take them from the model, so they update if you change it.

Have a look here for some details on kableExtra https://bookdown.org/yihui/rmarkdown-cookbook/kableextra.html.

6.3.4 Showing a Regression Model as a Figure

A table gives the exact numbers; a coefficient plot shows at a glance which predictors matter, in which direction, and how uncertain the estimates are. tidy(model, conf.int = TRUE) adds the 95% confidence intervals. Each dot is the change in the percentage of residents in very bad health associated with a 1 percentage point increase in the predictor, holding the other predictors constant. If an interval crosses the dashed line at 0, the coefficient is not statistically significant at the 5% level.

coef_data <- tidy(model, conf.int = TRUE) %>%
 filter(term != "(Intercept)") %>% # the intercept is not a predictor
 mutate(term = recode(term,
                      pct_No_qualifications = "No qualifications (%)",
                      pct_Males = "Males (%)",
                      pct_Higher_manager_prof = "Higher managerial and professional (%)"))

ggplot(coef_data, aes(x = estimate, y = term)) +
 geom_vline(xintercept = 0, linetype = "dashed", colour = "grey50") +
 geom_pointrange(aes(xmin = conf.low, xmax = conf.high)) +
 labs(
  title = "Predictors of very bad health",
  subtitle = "Districts of England and Wales, Census 2021",
  x = "Coefficient (95% confidence interval)",
  y = NULL
 ) +
 theme_minimal()

Here all predictors are percentages, so their coefficients are on comparable scales. If your predictors are in different units (e.g. income in £ and age in years), the size of the dots is not directly comparable: say so in the text, or standardise the predictors first.

NoteQuestion

Would you put both the regression table and the coefficient plot in your assignment? (Look at the lecture’s DOs and DON’Ts.)

6.4 Part 5: Play with the code

6.4.1 Task 1: Reproduce Figure 1 from the lecture

The Key Elements slide of the lecture shows Figure 1: Health and Highest Qualification, made with the FRS. Reproduce it with frs_adults:

  • stacked percentage bars, one bar per qualification group;
  • health ordered from Very Good to Very Bad, with a sequential palette (scale_fill_brewer(palette = "Blues"));
  • a descriptive title, axis labels, a legend title;
  • the source as a caption: labs(caption = "Source: Author's calculations based upon the Family Resources Survey 2016-17 (DWP/NCSR/ONS, 2018).").

6.4.2 Task 2: One figure for your assignment

Make one figure for your own research question and check it against this list (you can finish it at home):

6.4.3 Keep experimenting

  • Experiment with different variables and aesthetics to deepen your understanding of ggplot2.
  • Test modifying labels, themes, and colour schemes to create tailored visualisations.