Tutorial-06

Author

Kate Saunders

Visualisation in R: Facets and Group Aesthetic Mapping

Learning Objectives

  • Practice using small multiples to visualise your data

  • This will involve using facet_wrap and facet_grid

  • Also practice grouping your data by categorical variables for visualisation

Preparation

  • We expect you to be using an R project for all tutorials

  • Download the dataset from Moodle, boston_celtics.csv, and place it in a folder called data within your R Project.

Tasks

Building on tutorial 4, you will be creating visualisations in ggplot2 to analyse sporting statistics from the Boston Celtics NBA basketball team.

library(tidyverse)
library(here)
boston_celtics <- read_csv(here("data", "boston_celtics.csv"))

Task 1

Using facet_wrap recreate the following plot:

Hint: Look up geom_vline() to add the average team score. You may like to challenge yourself to also add the average team score for each season as well.

Task 2

Using facet_grid recreate the following plot:

Hint: What’s tricky here is changing the order (levels) of the categorical variables. The default for how categorical variables are displayed on panels of plots is always alphabetical.

boston_celtics = boston_celtics |>
  mutate(
    team_winner = 
      factor(team_winner, levels = c("Won", "Lost")),
    team_home_away = 
      factor(team_home_away, levels = c("Home", "Away"))
  )

We need to:

  • Tell R it’s a categorical variable we make it a factor type

  • Change the order of the levels for plotting using recode.

Here is a cheat sheet on factors you can download to help you.

Task 3

Use the group aesthetic mapping and facet_wrap to create the following plot:

Hint: You can adapt the colour scale from Tutorial 4 and the linewidth is increased from default.

Note I made a small mistake and the legend names were around the wrong way, so I have updated the figure.