Visualize in R using ggplot

Structure of the book

The first couple weeks will be focused on visualization using `ggplot`

  • Easy place to start

  • Part of the data exploration process

  • Not boring

What is ggplot?

  • ggplot2 is a structured system for building plots.

  • gg stands for “grammar of graphics”

    • The layered grammar of graphics a language for describing how to map data to visual components of a graphic layer-by-layer.
  • To make a plot, only need to specify DATA, AESTHETICS, GEOMETRY.

www.rforecology.com
ggplot(data = ChickWeight) + 
 geom_point(mapping = aes(x = Time, y = weight, color = Diet))

What is ggplot?

  • All ggplots contain:
    1. Geometric layers composed of…
      • Data
      • Aesthetic mapping
      • Geometric elements
      • Statistical transformations
      • Position adjustments
    2. Scales
    3. Facets
    4. Coordinate systems
    5. Themes

What is ggplot?

  • All ggplots contain:
    1. Geometric layers composed of…
      • Data
      • Aesthetic mapping
      • Geometric elements
      • Statistical transformations
      • Position adjustments
    2. Scales
    3. Facets
    4. Coordinate systems
    5. Themes

What is ggplot?

  • All ggplots contain:
    1. Geometric layers composed of…
      • Data
      • Aesthetic mapping
      • Geometric elements
      • Statistical transformations
      • Position adjustments
    2. Scales
    3. Facets
    4. Coordinate systems
    5. Themes

All layers are sourced from data.

head(diamonds)
# A tibble: 6 × 10
  carat cut       color clarity depth table price     x     y     z
  <dbl> <ord>     <ord> <ord>   <dbl> <dbl> <int> <dbl> <dbl> <dbl>
1  0.23 Ideal     E     SI2      61.5    55   326  3.95  3.98  2.43
2  0.21 Premium   E     SI1      59.8    61   326  3.89  3.84  2.31
3  0.23 Good      E     VS1      56.9    65   327  4.05  4.07  2.31
4  0.29 Premium   I     VS2      62.4    58   334  4.2   4.23  2.63
5  0.31 Good      J     SI2      63.3    58   335  4.34  4.35  2.75
6  0.24 Very Good J     VVS2     62.8    57   336  3.94  3.96  2.48

ggplot2-book.org

What is ggplot?

  • All ggplots contain:
    1. Geometric layers composed of…
      • Data
      • Aesthetic mapping
      • Geometric elements
      • Statistical transformations
      • Position adjustments
    2. Scales
    3. Facets
    4. Coordinate systems
    5. Themes

Aesethics map variables to visual attributes

What is ggplot?

  • All ggplots contain:
    1. Geometric layers composed of…
      • Data
      • Aesthetic mapping
      • Geometric elements
      • Statistical transformations
      • Position adjustments
    2. Scales
    3. Facets
    4. Coordinate systems
    5. Themes

Aesethics map variables to visual attributes

What is ggplot?

  • All ggplots contain:
    1. Geometric layers composed of…
      • Data
      • Aesthetic mapping
      • Geometric elements
      • Statistical transformations
      • Position adjustments
    2. Scales
    3. Facets
    4. Coordinate systems
    5. Themes

Aesethics map variables to visual attributes

What is ggplot?

  • All ggplots contain:
    1. Geometric layers composed of…
      • Data
      • Aesthetic mapping
      • Geometric elements
      • Statistical transformations
      • Position adjustments
    2. Scales
    3. Facets
    4. Coordinate systems
    5. Themes

Statistical transformations summarize values as a statistic to visualize

What is ggplot?

  • All ggplots contain:
    1. Geometric layers composed of…
      • Data
      • Aesthetic mapping
      • Geometric elements
      • Statistical transformations
      • Position adjustments
    2. Scales
    3. Facets
    4. Coordinate systems
    5. Themes

adjustments tweak the position of geom elements

What is ggplot?

  • All ggplots contain:
    1. Geometric layers composed of…
      • Data
      • Aesthetic mapping
      • Geometric elements
      • Statistical transformations
      • Position adjustments
    2. Scales
    3. Facets
    4. Coordinate systems
    5. Themes

maps values in the data to values in the aesthetic attributes (x-axis, y-axis, color, fill, etc. )

What is ggplot?

  • All ggplots contain:
    1. Geometric layers composed of…
      • Data
      • Aesthetic mapping
      • Geometric elements
      • Statistical transformations
      • Position adjustments
    2. Scales
    3. Facets
    4. Coordinate systems
    5. Themes

maps values in the data to values in the aesthetic attributes (x-axis, y-axis, color, fill, etc. )

What is ggplot?

  • All ggplots contain:
    1. Geometric layers composed of…
      • Data
      • Aesthetic mapping
      • Geometric elements
      • Statistical transformations
      • Position adjustments
    2. Scales
    3. Facets
    4. Coordinate systems
    5. Themes

specify how to display subsets of data as separate plots

What is ggplot?

  • All ggplots contain:
    1. Geometric layers composed of…
      • Data
      • Aesthetic mapping
      • Geometric elements
      • Statistical transformations
      • Position adjustments
    2. Scales
    3. Facets
    4. Coordinate systems
    5. Themes

maps position onto the plane of a plot

What is ggplot?

  • All ggplots contain:
    1. Geometric layers composed of…
      • Data
      • Aesthetic mapping
      • Geometric elements
      • Statistical transformations
      • Position adjustments
    2. Scales
    3. Facets
    4. Coordinate systems
    5. Themes

customise the non-data elements of the plot

What is ggplot?

  • All ggplots contain:
    1. Geometric layers composed of…
      • Data
      • Aesthetic mapping
      • Geometric elements
      • Statistical transformations
      • Position adjustments
    2. Scales
    3. Facets
    4. Coordinate systems
    5. Themes

Put it all together…

ggplot() +
  layer(
    data = diamonds, 
    mapping = aes(x = carat, y = price, color = depth),
    geom = "point", 
    stat = "identity", 
    position = "identity"
  ) +
   layer(
    data = diamonds, 
    mapping = aes(x = carat, y = price),
    geom = "smooth", 
    stat = "smooth",
    position = "identity"
  ) +
  coord_cartesian() +
  scale_x_continuous() +
  scale_y_continuous() +
  facet_null() +
  theme() 

What is ggplot?

  • All ggplots contain:
    1. Geometric layers composed of…
      • Data
      • Aesthetic mapping
      • Geometric elements
      • Statistical transformations
      • Position adjustments
    2. Scales
    3. Facets
    4. Coordinate systems
    5. Themes

Simplify…

ggplot(
  data = diamonds, 
  mapping = aes(x = carat, y = price)
) +
  geom_point(mapping = aes(color = depth)) +
  geom_smooth() 

Application

Let’s build a plot…

ggplot(data = mpg)

Application: Aesthetic mappings

Let’s build a plot…

ggplot(data = mpg) + 
  geom_point(mapping = aes(x = displ, y = hwy))

Application: Aesthetic mappings

Let’s build a plot…

ggplot(data = mpg) + 
  geom_point(mapping = aes(x = displ, y = hwy), color = "blue")

Application: Aesthetic mappings

Let’s build a plot…

ggplot(data = mpg) + 
  geom_point(mapping = aes(x = displ, y = hwy, color = class))

Application: Aesthetic mappings

Let’s build a plot…

ggplot(data = mpg) + 
  geom_point(mapping = aes(x = displ, y = hwy, color = class, size = cyl))

Application: Facets

Let’s build a plot…

ggplot(data = mpg) + 
  geom_point(mapping = aes(x = displ, y = hwy, color = class, size = cyl)) +
  facet_wrap(~ class, nrow = 2)

Application: Facets

Let’s build a plot…

ggplot(data = mpg) + 
  geom_point(mapping = aes(x = displ, y = hwy, color = class, size = cyl)) +
  facet_grid(drv~ class)

Application: Geometric objects

ggplot(data = mpg) + 
  geom_point(mapping = aes(x = displ, y = hwy))

ggplot(data = mpg) + 
  geom_smooth(mapping = aes(x = displ, y = hwy))

Application: Statistical transformations

ggplot(data = diamonds) + 
  geom_bar(mapping = aes(x = cut))

ggplot(data = diamonds) + 
  geom_boxplot(mapping = aes(x = cut, y = depth))

ggplot(data = diamonds) + 
  stat_summary(
    mapping = aes(x = cut, y = depth),
    fun.min = min,
    fun.max = max,
    fun = median
  )

Application: Position Adjustments

ggplot(data = diamonds) + 
  geom_bar(mapping = aes(x = cut, fill = clarity), position = "stack")

ggplot(data = diamonds) + 
  geom_bar(mapping = aes(x = cut, fill = clarity), position = "fill")

ggplot(data = diamonds) + 
  geom_bar(mapping = aes(x = cut, fill = clarity), position = "dodge")

Application: Position Adjustments

ggplot(data = mpg, mapping = aes(x = class, y = hwy)) + 
  geom_boxplot() +
  geom_point() 

ggplot(data = mpg, mapping = aes(x = class, y = hwy)) + 
  geom_boxplot() +
  geom_point(position = "jitter")

Application: Coordinates

ggplot(data = mpg, mapping = aes(x = class, y = hwy)) + 
  geom_boxplot()

ggplot(data = mpg, mapping = aes(x = class, y = hwy)) + 
  geom_boxplot() +
  coord_flip()

Application: Labels and scales

ggplot(data = mpg, mapping = aes(x = drv, y = hwy)) + 
  geom_boxplot(aes(color = drv)) +
  labs(
    title = "Miles per gallon on the highway",
    subtitle = "By transmission type ",
    x = "Transmission", y = "MPG on Highway"
  ) +
  scale_color_manual(
    breaks = c("4", "f", "r"),
    values = c("red", "green", "orange"),
    name = "DRV"
  ) +
  theme_bw()

Your turn: In class assignment

Make the following plot

To begin…

Install the following packages, if you haven’t already.

install.packages("tidyverse")
install.packages("palmerpenguins")

Once installed, load the packages into R.

library(tidyverse)
library(palmerpenguins)

Check out the data:

glimpse(penguins)
Rows: 344
Columns: 8
$ species           <fct> Adelie, Adelie, Adelie, Adelie, Adelie, Adelie, Adel…
$ island            <fct> Torgersen, Torgersen, Torgersen, Torgersen, Torgerse…
$ bill_length_mm    <dbl> 39.1, 39.5, 40.3, NA, 36.7, 39.3, 38.9, 39.2, 34.1, …
$ bill_depth_mm     <dbl> 18.7, 17.4, 18.0, NA, 19.3, 20.6, 17.8, 19.6, 18.1, …
$ flipper_length_mm <int> 181, 186, 195, NA, 193, 190, 181, 195, 193, 190, 186…
$ body_mass_g       <int> 3750, 3800, 3250, NA, 3450, 3650, 3625, 4675, 3475, …
$ sex               <fct> male, female, female, NA, female, male, female, male…
$ year              <int> 2007, 2007, 2007, 2007, 2007, 2007, 2007, 2007, 2007…
Variable Description
species a penguin’s species
island island in Palmer Archipelago
bill_length_mm length of a penguin’s bill, in mm.
bill_depth_mm depth of a penguin’s bill, in mm.
flipper_length_mm length of a penguin’s flipper, in mm.
body_mass_g body mass of a penguin, in grams.
sex penguin sex (female, male, NA)
year study year (2007, 2008, or 2009)

Check the data

penguins
# A tibble: 344 × 8
   species island    bill_length_mm bill_depth_mm flipper_length_mm body_mass_g
   <fct>   <fct>              <dbl>         <dbl>             <int>       <int>
 1 Adelie  Torgersen           39.1          18.7               181        3750
 2 Adelie  Torgersen           39.5          17.4               186        3800
 3 Adelie  Torgersen           40.3          18                 195        3250
 4 Adelie  Torgersen           NA            NA                  NA          NA
 5 Adelie  Torgersen           36.7          19.3               193        3450
 6 Adelie  Torgersen           39.3          20.6               190        3650
 7 Adelie  Torgersen           38.9          17.8               181        3625
 8 Adelie  Torgersen           39.2          19.6               195        4675
 9 Adelie  Torgersen           34.1          18.1               193        3475
10 Adelie  Torgersen           42            20.2               190        4250
# … with 334 more rows, and 2 more variables: sex <fct>, year <int>

How to build it….

out <- ggplot()

How to build it…. (data)

out <- ggplot(
  data = penguins
)

How to build it…. (data + aes)

out <- ggplot(
  data = penguins,
  mapping = aes(x = flipper_length_mm, y = body_mass_g)
)

How to build it…. (data + aes + geom)

out <- ggplot(
  data = penguins,
  mapping = aes(x = flipper_length_mm, y = body_mass_g)
) +
  geom_point()

How to build it…. (data + aes + geom)

out <- ggplot(
  data = penguins,
  mapping = aes(x = flipper_length_mm, y = body_mass_g)
) +
  geom_point(
    color = "orange"
  )

How to build it…. (data + aes + geom)

out <- ggplot(
  data = penguins,
  mapping = aes(x = flipper_length_mm, y = body_mass_g)
) +
  geom_point(
    color = "orange",
    shape = 2
  )

How to build it…. (data + aes + geom)

out <- ggplot(
  data = penguins,
  mapping = aes(x = flipper_length_mm, y = body_mass_g)
) +
  geom_point(
    color = "orange",
    shape = 3
  )

How to build it…. (data + aes + geom)

out <- ggplot(
  data = penguins,
  mapping = aes(x = flipper_length_mm, y = body_mass_g)
) +
  geom_point(
    color = "orange",
    shape = 3
  ) + 
  geom_smooth(
    method = "lm"
  )

How to build it…. (data + aes + geom)

out <- ggplot(
  data = penguins,
  mapping = aes(x = flipper_length_mm, y = body_mass_g)
) +
  geom_point(
    mapping = aes(color = species, shape = species),
    show.legend = F
  ) +
  geom_smooth(
    method = "lm"
  )

How to build it…. (data + aes + geom)

out <- ggplot(
  data = penguins,
  mapping = aes(x = flipper_length_mm, y = body_mass_g)
) +
  geom_point(
    mapping = aes(color = species, shape = species),
    show.legend = T
  ) +
  geom_smooth(
    method = "lm"
  ) 

How to build it…. (data + aes + geom)

out <- ggplot(
  data = penguins,
  mapping = aes(x = flipper_length_mm, y = body_mass_g)
) +
  geom_point(
    mapping = aes(color = species, shape = species)
  ) +
  geom_smooth(
    method = "lm"
  ) 

How to build it…. (data + aes + geom + labs)

out <- ggplot(
  data = penguins,
  mapping = aes(x = flipper_length_mm, y = body_mass_g)
) +
  geom_point(
    mapping = aes(color = species, shape = species)
  ) +
  geom_smooth(
    method = "lm"
  ) +
  labs(
    title = "Body mass and flipper length"
  ) 

How to build it…. (data + aes + geom + labs)

out <- ggplot(
  data = penguins,
  mapping = aes(x = flipper_length_mm, y = body_mass_g)
) +
  geom_point(
    mapping = aes(color = species, shape = species)
  ) +
  geom_smooth(
    method = "lm"
  ) +
  labs(
    title = "Body mass and flipper length",
    subtitle = "Dimensions for Adelie, Chinstrap, and Gentoo Penguins"
  ) 

How to build it…. (data + aes + geom + labs)

out <- ggplot(
  data = penguins,
  mapping = aes(x = flipper_length_mm, y = body_mass_g)
) +
  geom_point(
    mapping = aes(color = species, shape = species)
  ) +
  geom_smooth(
    method = "lm"
  ) +
  labs(
    title = "Body mass and flipper length",
    subtitle = "Dimensions for Adelie, Chinstrap, and Gentoo Penguins",
    x = "Flipper length (mm)", y = "Body mass (g)"
  ) 

How to build it…. (data + aes + geom + labs)

out <- ggplot(
  data = penguins,
  mapping = aes(x = flipper_length_mm, y = body_mass_g)
) +
  geom_point(
    mapping = aes(color = species, shape = species)
  ) +
  geom_smooth(
    method = "lm"
  ) +
  labs(
    title = "Body mass and flipper length",
    subtitle = "Dimensions for Adelie, Chinstrap, and Gentoo Penguins",
    x = "Flipper length (mm)", y = "Body mass (g)",
    color = "Species", shape = "Species"
  ) 

How to build it…. (data + aes + geom + labs + scales)

out <- ggplot(
  data = penguins,
  mapping = aes(x = flipper_length_mm, y = body_mass_g)
) +
  geom_point(
    mapping = aes(color = species, shape = species)
  ) +
  geom_smooth(
    method = "lm"
  ) +
  labs(
    title = "Body mass and flipper length",
    subtitle = "Dimensions for Adelie, Chinstrap, and Gentoo Penguins",
    x = "Flipper length (mm)", y = "Body mass (g)",
    color = "Species", shape = "Species"
  ) +
  scale_color_colorblind()

How to build it…. (data + aes + geom + labs + scales)

out <- ggplot(
  data = penguins,
  mapping = aes(x = flipper_length_mm, y = body_mass_g)
) +
  geom_point(
    mapping = aes(color = species, shape = species)
  ) +
  geom_smooth(
    method = "lm"
  ) +
  labs(
    title = "Body mass and flipper length",
    subtitle = "Dimensions for Adelie, Chinstrap, and Gentoo Penguins",
    x = "Flipper length (mm)", y = "Body mass (g)",
  ) +
  scale_color_manual(
    breaks = c("Adelie", "Gentoo", "Chinstrap"),
    values = c("black","#56B4E9", "#E69F00"),
    name = "Species"
  ) +
  scale_shape_manual(
    breaks = c("Adelie", "Gentoo", "Chinstrap"),
    values = c(22,23,24),
    name = "Species"
  )

How to build it…. (data + aes + geom + labs + scales)

out <- ggplot(
  data = penguins,
  mapping = aes(x = flipper_length_mm, y = body_mass_g)
) +
  geom_point(
    mapping = aes(color = species, shape = species)
  ) +
  geom_smooth(
    method = "lm"
  ) +
  labs(
    title = "Body mass and flipper length",
    subtitle = "Dimensions for Adelie, Chinstrap, and Gentoo Penguins",
    x = "Flipper length (mm)", y = "Body mass (g)",
  ) +
  scale_color_manual(
    breaks = c("Adelie", "Gentoo", "Chinstrap"),
    values = c("black","#56B4E9", "#E69F00"),
    name = "Species"
  ) +
  scale_shape_manual(
    breaks = c("Adelie", "Gentoo", "Chinstrap"),
    values = c(22,23,24),
    name = "Species"
  )

How to build it…. (data + aes + geom + labs + scales)

out <- ggplot(
  data = penguins,
  mapping = aes(x = flipper_length_mm, y = body_mass_g)
) +
  geom_point(
    mapping = aes(color = sex, shape = species)
  ) +
  labs(
    title = "Body mass and flipper length",
    subtitle = "Dimensions for Adelie, Chinstrap, and Gentoo Penguins",
    x = "Flipper length (mm)", y = "Body mass (g)",
  ) +
  scale_color_manual(
    breaks = c("male", "female", NA),
    values = c("blue", "pink", "#E69F00"),
    name = "Sex"
  ) +
  scale_shape_manual(
    breaks = c("Adelie", "Gentoo", "Chinstrap"),
    values = c(22,23,24),
    name = "Species"
  ) + 
  facet_grid(.~species)