1.20 Advanced ggplot2 & Data Visualization Principles

Facets

data(penguins)
library(ggplot2)
library(dplyr)
theme_set(theme_bw())
penguins |>
  filter(!is.na(bill_len) & !is.na(flipper_len) & !is.na(sex)) |>
ggplot(aes(y = bill_len, x = flipper_len, color = species)) + 
  geom_point() + facet_wrap(~sex)

A set of two scatter plots of penguin dimensions, one for female penguins and one for male penguins. The x-axis shows flipper length in mm, the y-axis shows bill length in mm. Points are colored by species, and it is clear that across all 3 species (gentoo, adelie, chinstrap), female penguins are smaller than male penguins, though the difference is slight for Adelie penguins.

Facets

facet_xxx(~variable_name, scales = ..., space = ...)

  • xxx: wrap or grid.
    • grid allows var1 ~ var2, rows ~ cols
    • wrap allows ~var1
    • With both, you can (but probably shouldn’t) use var1 + var2 to get a combination
  • scales = fixed, free_x,free_y, orfree` (e.g. x and y)
    • free options work best with facet_wrap
    • free scales allow the range of the subplot to reflect only the data in that facet
    • comparisons get visually harder to make, but it saves space
  • space = free_x, free_y, fixed – only one column can be free space
    • This changes the amount of space allocated to each facet (and also changes the range)

Facets – demo

p <- penguins |>
  ggplot(aes(x = flipper_len, y = bill_len, color = sex)) +
  geom_point(alpha = .5) +
  theme(legend.position = "bottom")
p
1
Aesthetic specification and Geom selection. Plot points as 50% transparent to allow seeing the overplotting and make it easier to figure out which points are NA.
2
Change the location of the legend using the previously defined theme commands

A scatterplot showing measurements of three species of penguin, Chinstrap, Gentoo, and Adelie. The x-axis shows flipper length in mm, the y-axis shows bill length in mm. Points are colored by sex (female, male, NA/unknown). There are 3 rough clusters of points, each with male and female groupings. In each cluster, female penguins are smaller than male penguins, though the difference is slight for Adelie penguins.

Facets – demo

p + 
  facet_wrap(~species)
1
Facet by species, and allow facets to wrap around into multiple rows.

A set of three scatter plots of penguin dimensions, one for each species, Chinstrap, Gentoo, and Adelie.  The x-axis shows flipper length in mm, the y-axis shows bill length in mm. Points are colored by sex (female, male, NA/unknown), and it is clear that across all 3 species (gentoo, adelie, chinstrap), female penguins are smaller than male penguins, though the difference is slight for Adelie penguins. Of the 3 species, gentoo penguins have the largest dimensions for both bill and flipper length, Adelie penguins have the smallest dimensions, and Chinstrap penguins have about the same flipper length as Adelie penguins but have longer bills, on average, across both sexes.

Facets – free_x scales

p +
  facet_wrap(~species, scales = "free_x")
1
Wrap facets around. Set facets to have unconstrained x-scales, which adjusts the range of x for the subplots to fit each individual range of data.

A set of three scatter plots of penguin dimensions, one for each species, Chinstrap, Gentoo, and Adelie.  The x-axis shows flipper length in mm, the y-axis shows bill length in mm. Points are colored by sex (female, male, NA/unknown), and it is clear that across all 3 species (gentoo, adelie, chinstrap), female penguins are smaller than male penguins, though the difference is slight for Adelie penguins. Of the 3 species, gentoo penguins have the largest dimensions for both bill and flipper length, Adelie penguins have the smallest dimensions, and Chinstrap penguins have about the same flipper length as Adelie penguins but have longer bills, on average, across both sexes.

Facets – free_x for space and scales

p + 
  facet_wrap(~species, scales = "free_x", space = "free_x")
1
Facet by species, and allow facets to wrap around into multiple rows. Allow space and scales for each facet to vary.

A set of three scatter plots of penguin dimensions, one for each species, Chinstrap, Gentoo, and Adelie.  The x-axis shows flipper length in mm, the y-axis shows bill length in mm. Points are colored by sex (female, male, NA/unknown), and it is clear that across all 3 species (gentoo, adelie, chinstrap), female penguins are smaller than male penguins, though the difference is slight for Adelie penguins. Of the 3 species, gentoo penguins have the largest dimensions for both bill and flipper length, Adelie penguins have the smallest dimensions, and Chinstrap penguins have about the same flipper length as Adelie penguins but have longer bills, on average, across both sexes.

Facets – free_y scales

p + 
  facet_wrap(~species, scales = "free_y")
1
Wrap facets around. Set facets to have unconstrained y-scales, which adjusts the range of x for the subplots to fit each individual range of data.

A set of three scatter plots of penguin dimensions, one for each species, Chinstrap, Gentoo, and Adelie.  The x-axis shows flipper length in mm, the y-axis shows bill length in mm. Points are colored by sex (female, male, NA/unknown), and it is clear that across all 3 species (gentoo, adelie, chinstrap), female penguins are smaller than male penguins, though the difference is slight for Adelie penguins. Of the 3 species, gentoo penguins have the largest dimensions for both bill and flipper length, Adelie penguins have the smallest dimensions, and Chinstrap penguins have about the same flipper length as Adelie penguins but have longer bills, on average, across both sexes.

Facets – free_y for space and scales

p + 
  facet_wrap(
    ~species,
    scales = "free_y",
    space = "free_y")
1
Facet by species, and allow facets to wrap around into multiple rows. Allowing scales and space on the y-axis to vary forces ggplot2 to lay the facets out in rows, rather than columns.

A set of three scatter plots of penguin dimensions, one for each species, Chinstrap, Gentoo, and Adelie.  The x-axis shows flipper length in mm, the y-axis shows bill length in mm. Points are colored by sex (female, male, NA/unknown), and it is clear that across all 3 species (gentoo, adelie, chinstrap), female penguins are smaller than male penguins, though the difference is slight for Adelie penguins. Of the 3 species, gentoo penguins have the largest dimensions for both bill and flipper length, Adelie penguins have the smallest dimensions, and Chinstrap penguins have about the same flipper length as Adelie penguins but have longer bills, on average, across both sexes.

Theming

Included in ggplot2

Demonstrating the 9 themes which are included in the ggplot2 package: theme_bw (black plot outline, light grey grid lines, minimal other annotations), theme_classic(x and y axis, no grid lines, no top or right plot boundary), theme_dark (dark grey background, even darker grey grid lines, with tick marks and axis labels on white outside the plot boundary), theme_grey, the default, which has light grey plot interior, light/white grid lines, and a white exterior, with no outline, theme_light, which has a light grey outline and light grey grid lines, theme_linedraw, which has a black plot outline and darker grey grid lines, with a white plot background, theme_minimal, which has no plot outline and very light grey gridlines, theme_test, which has a black plot outline and no grid lines, and theme_void, which has no axes, no tick marks, no grid lines, and no plot outline, with geoms plotted on a white background.

ggplot2 package themes

ggthemes package

The `ggthemes` package function `theme_base()`

base

The `ggthemes` package function `theme_calc()`

calc

The `ggthemes` package function `theme_clean()`

clean

The `ggthemes` package function `theme_economist-white()`

economist-white

The `ggthemes` package function `theme_economist()`

economist

The `ggthemes` package function `theme_excel-new()`

excel-new

The `ggthemes` package function `theme_excel()`

excel

The `ggthemes` package function `theme_few()`

few

The `ggthemes` package function `theme_fivethirtyeight()`

fivethirtyeight

The `ggthemes` package function `theme_foundation()`

foundation

The `ggthemes` package function `theme_gdocs()`

gdocs

The `ggthemes` package function `theme_hc()`

hc

The `ggthemes` package function `theme_igray()`

igray

The `ggthemes` package function `theme_map()`

map

The `ggthemes` package function `theme_pander()`

pander

The `ggthemes` package function `theme_par()`

par

The `ggthemes` package function `theme_solarized()`

solarized

The `ggthemes` package function `theme_solarized2()`

solarized2

The `ggthemes` package function `theme_solid()`

solid

The `ggthemes` package function `theme_stata()`

stata

The `ggthemes` package function `theme_tufte()`

tufte

The `ggthemes` package function `theme_wsj()`

wsj

 

 

library(ggthemes) and p + theme_xxx()

ggthemr package

A demonstration of ggthemr's camouflague theme

camoflague

A demonstration of ggthemr's chalk theme

chalk

A demonstration of ggthemr's copper theme

copper

A demonstration of ggthemr's dust theme

dust

A demonstration of ggthemr's earth theme

earth

A demonstration of ggthemr's flat theme

flat

A demonstration of ggthemr's flat dark theme

flat-dark

A demonstration of ggthemr's fresh theme

fresh

A demonstration of ggthemr's grape theme

grape

A demonstration of ggthemr's grass theme

grass

A demonstration of ggthemr's greyscale theme

greyscale

A demonstration of ggthemr's light theme

light

A demonstration of ggthemr's lilac theme

lilac

A demonstration of ggthemr's pale theme

pale

A demonstration of ggthemr's sea theme

sea

A demonstration of ggthemr's sky theme

sky

A demonstration of ggthemr's solarized theme

solarized

 

Just because you can doesn’t mean you should

Making Good Graphics

Charts vs. Tables

Would you rather have a chart, or a data table

  • to understand a relationship?

  • to estimate a statistic?

  • to compute exact quantities?

  • to explain something?



Human retinas have a “bandwidth” of 8.75 megabits per second1

Reading speed is ~ 200 words per minute2, or ~ 0.0229 megabits per second

Spot the Difference

Scatterplots with colored points (left) and varying point shape (right). In each plot, it is relatively easy to see one point that stands out from the others.

Scatterplots with colored points (left) and varying point shape (right). In each plot, it is relatively easy to see one point that stands out from the others.

Spot the Difference

Scatterplots with colored points (left) and varying point shape (right). In each plot, it is relatively easy to distinguish two sets of points, however, in the right plot, there is one point which is not part of either set but has characteristics of both.

Dual encoding - shape and color mapped to the same variable

Scatterplots with colored points (left) and varying point shape (right). In each plot, it is relatively easy to distinguish two sets of points, however, in the right plot, there is one point which is not part of either set but has characteristics of both.

Encoding shape and color separately

Accuracy of Graphical Judgments

Most Accurate

  1. Position along a common scale
  2. Position along nonaligned scale
  3. Length
  4. Curvature, Angle, Slope
  5. Area
  6. Volume, Density, Color saturation
  7. Color hue

Least Accurate

Position, aligned scale

Position, aligned scale

Position, non-aligned scale

Position, non-aligned scale

Length

Length

 

Curvature

Curvature

 

Angle

Angle

 

Slope

Slope

 

Area

Area

 

 

Volume

Volume

 

Point Density

Point Density

 

 

Color saturation

Color saturation

 

Color hue

Color hue

 

Well designed charts make it easy for the viewer to think about the data, rather than the chart

To design a good graphic, first consider:

  • What is the most important comparison?

  • What secondary comparisons do you want to show?

Example - Penguin Bills

Reorder species variable levels
penguins_reorder <- penguins |>
  mutate(
    species = factor(
      species,
      levels = c("Chinstrap",
                 "Adelie",
                 "Gentoo"),
      ordered = T)
  ) 
1
Specify mutate on species, creating a factor variable
2
Level order should be set to this
3
Specify that the factor is an ordered factor (e.g. don’t order alphabetically by default)
Scatterplot, colored by sex and facetted by species.
p1 <- penguins_reorder |>
  filter(!is.na(sex)) |>
  ggplot(aes(x = bill_len,
             y = bill_dep,
             color = sex)) +
  geom_point(alpha = 0.5) +
  coord_fixed(xlim = c(30, 60),
              ylim = c(12.5, 22.5)) +
  facet_wrap(~species, ncol = 2) +
  labs(x = "Bill Length (mm)",
       y = "Bill Depth (mm)",
       color = "Sex") +
  theme(legend.position = "bottom")
1
Rearrange penguin species order from alphabetical to something that makes it easier to compare chinstrap to both gentoo and adelie. (extra code)
2
Drop penguins with unknown sex, just to make this a bit easier.
3
aesthetic mappings
4
geometry specification - use transparent points to make it easier to see the overlap.
5
Fix the aspect ratio so that one unit of the x-axis is the same as one unit of the y-axis. As both are in mm, this makes physical sense. Also set x and y plot limits (helps me size the pictures correctly – not necessary in general)
6
Facet by the selected variable
7
Set x, y, and legend labels
8
Put legends at the bottom of the plot.

 

Scatterplot, colored by species and facetted by sex.
p2 <- penguins |>
  filter(!is.na(sex)) |>
  ggplot(aes(x = bill_len,
             y = bill_dep,
             color = species)) +
  geom_point(alpha = 0.5) +
  coord_fixed(xlim = c(30, 60),
              ylim = c(12.5, 22.5)) +
  facet_wrap(~sex, ncol = 1) +
  labs(x = "Bill Length (mm)",
       y = "Bill Depth (mm)",
       color = "Species") +
  theme(legend.position = "bottom")
2
Drop penguins with unknown sex, just to make this a bit easier.
3
aesthetic mappings
4
geometry specification - use transparent points to make it easier to see the overlap.
5
Fix the aspect ratio so that one unit of the x-axis is the same as one unit of the y-axis. As both are in mm, this makes physical sense. Also set x and y plot limits (helps me size the pictures correctly – not necessary in general)
6
Facet by the selected variable
7
Set x, y, and legend labels
8
Put legends at the bottom of the plot.

Two sets of facetted scatterplots. In the first figure, a scatterplot of penguin bill length (x) by bill depth (y) in mm, with separate subplots for Chinstrap, Adelie, and Gentoo penguins. Points are colored by sex (M, F, NA). Adelie penguins have much smaller bill length than the other species, and Gentoo penguins have much smaller bill depth than the other species. In all species, however, female penguins have smaller bill dimensions than male penguins. In the second figure, a scatterplot of penguin bill length (x) by bill depth (y) in mm, with separate subplots for males and females. Points are colored by species (Adelie, Gentoo, Chinstrap). Adelie penguins have much smaller bill length than the other species, and Gentoo penguins have much smaller bill depth than the other species. In all species, however, female penguins have smaller bill dimensions than male penguins.

  • Which comparisons are easier with each type of plot?

  • Does it help to have reordered the species in the left plot so that you can compare bill depth and length?

Cognitive Limits

Short Term Memory

  • Are there colors associated with your variables?

    • cold / hot, / ,        amount of plant cover       ,        snow depth       

    Using common color associations reduces cognitive load

  • Minimize categories: Keep # legend entries \(\leq 7\)

    \(7 \pm 2\) is thought to be the limit of short-term memory.

Graphical Conventions

  • X-axis: left is smaller, right is larger
  • Y-axis: bottom is smaller, top is larger
  • Color: less saturated (pastel/white) is smaller, more saturated (bold color) is larger


- Use the smallest dimension possible - don’t use area when length will do - fake 3D perspective is misleading - Pixel accuracy - the number of pixels should match the magnitude of the data! - Infographics, logos, etc. look cute (sometimes?) but are often less accurately perceived.

Color Choices

Hall of Graphical Shame

Bar Chart Y-Axis should start at zero!

A bar chart showing weekly high temperatures where the axis starts at 92 and goes to 94, making a 2 degree Fahrenheit jump look massive.

Fox 8, New Orleans, Source

Stacked Area Maps aren’t a thing

A US map showing the ethnic composition of the US in 1960 (west coast), 2010 (midwest), and the projected composition in 2060 (east coast). The predicted proportion of white individuals drops from 85% to 64% to 43%; the proportion of the population that is black stays roughly the same at around 10-13%, and the proportion of the population that is hispanic is under 10% in 1960, at 16% in 2010, and up to 31% in 2060. The mpa utterly does not explain the massive drop in population due to the presence of Canada and the great lakes between 2010 and 2060, nor does it explain how to interpret the rise in population in the 2000-2020 era due to the presence of Texas. Alaska and Hawaii are also ... neglected, though they are colored in as if they're representing the white proportion of the population despite not being contiguous with the rest of the country.

Nightly News with Brian Williams, 2014 Source
  • Color scheme is also a problem
  • What do we even do with Alaska/Hawaii?

Adding “Charts**” to pictures is not a good idea

**Calling this a chart is generous

A screenshot of a promoted social media post from BetMGM that reads 'Mike Glennon has 1 win since 2014. Glennon's earned over 5.3 mil per win in the NFL (6-24)'. A picture is included, titled 'Mike Glennon Career Earnings', with a head and shoulders of a man (presumably mike glennon) and a set of colored bars (not scaled to the amount shown?) with team logos and the amount of money earned with each team. The overall effect is to make the head look something like a rainbow giraffe with a WTF look on its face.

The Movement to end bad charts?

A screenshot of a social media post showing semi-egg shaped chart divided into chunks with vertical lines, labeled 'Agree with NEITHER', 'Agree with ONE', 'Agree with BOTH'. There seems to be no connection between the numbers shown on the chart and the colored area of each section. The chart title says 'What is the Movement', and then says '21 million Americans believe both Biden Illegitimate - Force justified to restore Trump'.

A horizontal stacked bar chart showing that the original chart was highly misleading: in reality, given statements 'Biden Illegitimate' and 'force is justified to restore Trump', 74% of the US agreed with neither statement, 18% agreed with one, and 8% agreed with both. The proportion of the area allocated to each statement in the original chart, respectively, is 45%, 21%, and 33%, as measured using image editing software.

The Only Thing Worse than a Pie Chart is…

A stack of pie slices with numerical labels. It is not clear what the original survey was asking, but the visual is terrible anyways.

The “Piemaster” source

A floating cylinder set with pie charts at the top of each cylinder. Each cylinder hovers in 3d space and has a rainbow of slices.

A pie? step? bubble? bar? chart that has 3D when only one is required.

DISQUS, Source

 

A pie chart from the 2012 Republican primary where there are 3 slices, showing 63% back Huckabee, 70% back Palin, and 60% back Romney; these proportions label three roughly equal pie slices.

Fox News, circa 2012

My Contribution

A bad graphics challenge contribution showing pie chart-line hybrids with facets, a bad color scheme that is colorblind unfriendly, a terrible mapping between diameter and number of observations that creates a non-representative area. The facet strips are also incredibly low contrast.

  • pie charts
  • used as bubbles in a bubble-line chart hybrid
  • fill is not colorblind friendly
  • radius of pies mapped to data points, so area (perceived) is mapped to \(n^2\), not \(n\)
  • y-axis range goes below 0 – not possible
  • facet titles do not have enough contrast
  • grid lines are incredibly low contrast and dotted – not really visible.