ggplot2 graphics companion

Last updated: 09 July 2020


The Graphics Companion provides the R code for different data visualisations that can be created using the ggplot2 package.

The Companion adopts the structure of the Financial Times’ Visual Vocabulary by categorising different chart types by the data relationships that they best illustrate.

The data used throughout the Companion derive from a subset of Hans Rosling’s Gapminder World which are available in the gapminder R package. Data on life expectancy at birth, GDP per capita and total population are provided for 142 countries between 1952 and 2007.

Setup

You need to install - but only once - the tidyverse package and load it into your R session. ggplot2 is part of the tidyverse suite of R tools for data science.

# install.packages('tidyverse')
library(tidyverse)

All of the example plots below use data contained in the gapminder R package which also needs to be installed / loaded:

# install.packages('gapminder')
library(gapminder)

Lastly, we need to load the Trafford Data Lab’s ggplot2 theme.

source("https://raw.githubusercontent.com/traffordDataLab/assets/601e80334e0d78dfe913685561196b8b6fc278a7/theme/ggplot2/theme_lab.R")

If you wish to use an alternative theme simply swap out the theme_lab() function with a different ggplot2 theme or use one from the ggthemes package.


Change over time

Single line chart

df <- filter(gapminder, country == "Argentina") %>% 
  mutate(year = as.Date(paste(year, "-01-01", sep = "", format='%Y-%b-%d')))

ggplot(df, aes(x = year, y = lifeExp)) +
  geom_line(colour = "#fc6721", size = 1) +
  geom_point(colour = "#fc6721", size = 2) +
  scale_x_date(breaks = df$year, date_labels = "%Y") +
  scale_y_continuous(limits = c(0, max(df$lifeExp)), labels = scales::comma) +
  labs(title = "",
   subtitle = "Life expectancy in Argentina, 1952-2007",
   caption = "Source: Gapminder.org  |  @traffordDataLab",
   x = "",
   y = "Age (years)") +
  theme_lab() +
  theme(panel.grid.major.x = element_blank())