--- title: "Lab: Data Visualisation with ggplot" author: "Gabriele Filomena" date: today format: html --- ::: {.callout-important title="Make 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](https://github.com/GDSL-UL/stats/blob/main/labs/05.Visualisation.qmd) and click the **Download raw file** button (the arrow icon at the top right of the file). Alternatively, right-click [this link](https://raw.githubusercontent.com/GDSL-UL/stats/main/labs/05.Visualisation.qmd) 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](../general/setup.qmd) 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](https://canvas.liverpool.ac.uk/courses/93312/pages/family-resource-survey-2016-17?module_item_id=2727712) and upload it to a new folder `data/FRS` in RStudio (see [Setup](../general/setup.qmd), section 5). You don't need to change any of the file paths in the code. The lecture's slides can be found [here](https://github.com/GDSL-UL/stats/blob/main/lectures/lecture05.pdf). ## 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 = , y = , )) + + ``` ### **`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. ```{r} library(ggplot2) ``` **Example:** Let's load the data first: ```{r} census_data <- read.csv("../data/Census2021/EW_DistrictPercentages.csv") ``` Plotting Number of residents vs age (mean). ```{r} ggplot(data = census_data, aes(x = Residents, y = mean_age)) + geom_point() ``` ### 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()`** ```{r} ggplot(census_data, aes(x = Residents, y = mean_age, color = factor(Region))) + geom_point(size = 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** ```{r} ggplot(census_data, aes(x = Residents, y = mean_age, color = factor(Region), size = pct_Very_bad_health)) + geom_point() ``` ::: {.callout-note title="Question"} What's missing in the plot above? How can this be improved? ::: ### 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. ```{r} ggplot(census_data, aes(x = Residents, y = mean_age)) + geom_point() + facet_wrap(~Region) ``` ::: {.callout-note title="Question"} What are the issues here? ::: ### 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** ```{r} ggplot(data = census_data, aes(x = Residents, y = mean_age)) + geom_point() + theme_void() + labs(title = "Visualisation with Void Theme") ``` ::: {.callout-note title="Question"} What do you think? Is this any good? ::: ### 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 ```{r} # Automatically determine the number of colors needed num_levels <- length(unique(census_data$Region)) num_levels ``` 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: ```{r} 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. ```{r} 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") ``` ::: {.callout-note title="Question"} `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. ```{r} 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() ``` ::: {.callout-note title="Question"} 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. ::: ::: {.callout-note collapse="true" title="Reference: functions associated to scales (click to open)"} | **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))` | ::: ### 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 `+`): ```{r} #| eval: false # labels labs( title = "Plot Title", x = "X-Axis Label", y = "Y-Axis Label", color = "Legend Title", caption = "Source: ..." ) ``` Flipping: ```{r} # 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. ## 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.** ```{r} library(tidyverse) # dplyr, tidyr and forcats (we used fct_relevel in Lab 03) 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. ```{r} 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) levels(frs_adults$highest_qual) ``` ### Distribution of 1 Numerical variable: **Histogram** ```{r} 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. ::: {.callout-tip title="Task"} 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)* ```{r} 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)* ```{r} # 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. ```{r} library(scales) # For label_comma() 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. #### 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. ```{r} 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. ```{r} 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() ``` ::: {.callout-tip title="Task"} 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? ::: ### 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. ```{r} 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. ### 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. ```{r} 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. ```{r} library(ggridges) # need a library for this 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") ``` **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. ```{r} 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. ```{r} 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. ```{r} # Create a cross-tabulation of observed counts cross_tab <- table(frs_adults$health, frs_adults$highest_qual) cross_tab # 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). ```{r} # 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)) ``` ::: {.callout-note title="Question"} 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` ```{r} # 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. ```{r} # 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") ``` ### Visualising Relationships: **2 Numerical Variables: Scatterplot** ```{r} 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() ``` ::: {.callout-warning title="Districts 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** ```{r} 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() ``` ::: {.callout-tip title="Task"} 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. ```{r} library(corrplot) # 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. ```{r} # 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()`: ```{r} 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`: ```{r} 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)") ``` ::: {.callout-note collapse="true" title="Optional: the same with ggplot"} If you want the `ggplot2` look, you need to build a long table with one row per pair of variables and per district. ```{r} # 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. ```{r} 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. ```{r} 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" ) ``` ## Part 3: Publication-Ready Tables We will be using `kableExtra` to create nicely formatted tables for a series of outputs in RStudio: ```{r} library(kableExtra) ``` ### 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 ```{r} library(vtable) # Generate the summary table st(census_data, vars = c("pct_Very_bad_health", "pct_No_qualifications", "pct_Males", "pct_Higher_manager_prof"), out = 'kable') ``` ### 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. ```{r} # 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 ``` ```{r} 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))) ``` - **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". ### 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. ```{r} # Load required libraries library(broom) # 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. ```{r} summary(model) ``` 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. ```{r} 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 ```{r} 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 = "") ``` - `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` . ### 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. ```{r} 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. ::: {.callout-note title="Question"} Would you put both the regression table and the coefficient plot in your assignment? (Look at the lecture's DOs and DON'Ts.) ::: ## Part 5: Play with the code ### 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).")`. ### 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): - [ ] The chart type matches your variables (look back at the lecture). - [ ] Descriptive title, axis labels with units, legend title. - [ ] Figure number and source in the caption. - [ ] Categories in a meaningful order; palette matching the variable (sequential, diverging or qualitative). - [ ] No data removed by axis limits (zoom with `coord_cartesian()` or use a log scale). - [ ] With thousands of points (e.g. the FRS), points are transparent (`geom_point(alpha = 0.1)`) so the dense areas stay readable. - [ ] The figure is referenced and discussed in your text, and the same results are not repeated in a table. ### 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.