Summary and Setup
This lesson introduces ggplot2 for learners with basic R
experience. It is designed as a short, focused session (approximately 2
hours).
The lesson assumes familiarity with the R language and the RStudio
interface. It begins by introducing the grammar of graphics, which
underpins how ggplot2 constructs plots. Using the built-in
mpg dataset, learners will explore how to create different
types of visualisations and how the choice of plot depends on the
question being asked.
This lesson focuses on the fundamentals of data visualisation using ggplot2. While examples may reference how plots are used in statistical contexts, it does not cover statistical analysis.
Participants should have completed an introductory R course (e.g. R for Reproducible Scientific Analysis or have equivalent experience. This includes familiarity with RStudio, running scripts, and working with data frames.
R and RStudio
This lesson assumes you have R and RStudio installed on your computer.
- Download and install the latest version of R.
- Download and install RStudio. RStudio is an application (an integrated development environment or IDE) that facilitates the use of R and offers a number of nice additional features. You will need the free Desktop version for your computer.
Required R packages
For this lesson we will use the package tidyverse.
The tidyverse is a beginner-friendly collection of R
packages designed specifically for data science that share a unified
design philosophy, grammar, and data structure. It simplifies data
importing, cleaning, and manipulation, making R much more intuitive to
learn and read.
R
install.packages("tidyverse")
ggplot2 is the premier data visualization package within
the tidyverse, meaning it automatically loads when you call
library(tidyverse) and seamlessly integrates with all other
tools in the collection.
Check the package installed correctly by loading the
ggplot2 library.
R
library(ggplot2)
Data
We will use the mpg dataset that is packaged with
ggplot.
R
# View the dataset
head(mpg)
OUTPUT
# A tibble: 6 × 11
manufacturer model displ year cyl trans drv cty hwy fl class
<chr> <chr> <dbl> <int> <int> <chr> <chr> <int> <int> <chr> <chr>
1 audi a4 1.8 1999 4 auto(l5) f 18 29 p compact
2 audi a4 1.8 1999 4 manual(m5) f 21 29 p compact
3 audi a4 2 2008 4 manual(m6) f 20 31 p compact
4 audi a4 2 2008 4 auto(av) f 21 30 p compact
5 audi a4 2.8 1999 6 auto(l5) f 16 26 p compact
6 audi a4 2.8 1999 6 manual(m5) f 18 26 p compact