1.19 ggplot2

Categorizing Charts

The cover of *Semiology of Graphics* by Jacques Bertin.

Whole Textbooks have been written on the subject

The Grammar of Graphics

The Grammar of Graphics

  • A chart is like a single word
    • “pie chart”, “bar chart”, “line chart”, “scatter plot”
    • specific instance of a more general object
    • some charts that look similar are actually very different - e.g. a bar chart and a histogram.
  • A graphic is a specification of the relationship between visual forms and mathematical expressions

The Grammar of Graphics

A grammar of graphics is

  • a set of rules and conventions
  • to describe these relationships
  • in a structured way

We start with the data and the axes.

The Grammar of Graphics

A data table with 6 variables, and a coordinate plane.

The Grammar of Graphics

A data table with 6 variables, and a coordinate plane. Arrows show the mapping of v1 (the first column in the table) to the x-axis, and v2 (the second column in the table) to the y-axis.

The Grammar of Graphics

A data table with 6 variables, and a coordinate plane. Arrows show the mapping of v1 (the first column in the table) to the x-axis, and v2 (the second column in the table) to the y-axis. A ggplot command, `ggplot(data, aes(x = v1, y = v2))` is shown over the arrows.

The Grammar of Graphics

data("penguins")
library(ggplot2)

ggplot(
  penguins, 
  aes(x = bill_len, 
      y = flipper_len)
)

A blank canvas showing the x-axis, bill length, and the y-axis, flipper length. Nothing else is shown on the chart.

The Grammar of Graphics

ggplot(
  data = <dataset>,
  aes(<mappings>)
) + 
  geom_function(
    aes(<additional mappings>), # <- This line is optional
    stat = <stat>, position = <position>) + 
  coordinate_function() + 
  facet_function() + 
  scale_function() + 
  theme_function()

You can layer multiple geoms together to get a more complicated graphic

Adding Things to the Plot

Geometric Objects

Next, we specify the geometric object we want to use to show the data.

Each geom has required aesthetic mappings as well as optional mappings.

geom required aesthetics optional aesthetics
point x, y color, shape, size, alpha
text x, y, label color, shape, size, angle, alpha, font family, font face, hjust, vjust
line x, y color, group, linetype, size
rect xmin, xmax, ymin, ymax color, fill, alpha, linetype, size
abline intercept, slope alpha, color, linetype, size
segment x, y, xend, yend alpha, color, linetype, size
bar x alpha, color, fill, linetype, size, weight

A screenshot of the ggplot2 cheat sheet available at https://opensource.posit.co/resources/cheatsheets/data-visualization/data-visualization.pdf

Consult the ggplot2 reference card to see all the geoms and their required mappings

Geometric Objects

A rectangle, with the lower left corner highlighted with an orange dot and orange text, (xmin, ymin), and the top right corner highlighted with a blue dot and text (xmax, ymax). There are arrows pointing at the border labeled color: border, linetype: border, size: border, and arrows pointing at the interior labeled alpha: transparency, fill: inside.

geom_rect

In the center of the figure, there is a word, label, sitting on top of a blue dot, with blue coordinates (x,y) underneath. An arrow points left to text: hjust: horizontal justification (alignment), 0=left, 0.5=center, 1=right. An arrow points  up from label, and says: vjust: vertical justification (alignment), 0=bottom, 0.5=center, 1=top. On the right of the figure, there is a horizontal line with a ray coming up from the left side, and on the ray there is text 'angle'. Below the label, there is a box with 'font family' written in several different fonts.

geom_text

geom_line

geom_line

Geometric Objects

data("penguins")
library(ggplot2)

ggplot(
  penguins, 
  aes(x = bill_len, 
      y = flipper_len)
) + 
  # aes is inherited from 
  # ggplot() statement
  geom_point()

A scatterplot showing the x-axis, bill length, and the y-axis, flipper length.

Geometric Objects

data("penguins")
library(ggplot2)

ggplot(
  penguins, 
  aes(x = bill_len, 
      y = flipper_len, 
      color = species)
) + 
  # aes is inherited from 
  # ggplot() statement
  geom_point() 

A scatterplot showing the x-axis, bill length, and the y-axis, flipper length. Points are colored by the species of the penguin.

  • Choices of colors for each species are made automatically
    (but can be customized w/ more code)
  • Legend appears automatically
  • One line of code changes

Position Adjustments

Arrange geoms that would otherwise use the same space

p <- ggplot(data = penguins, aes(x = species, fill = sex)) +
  theme(legend.position = "bottom")

p + geom_bar(position = "stack") + ggtitle("Position: Stack")
p + geom_bar(position = "dodge") + ggtitle("Position: Dodge")
p + geom_bar(position = "fill") + ggtitle("Position: Fill")

Position Adjustments

Arrange geoms that would otherwise use the same space

p <- ggplot(penguins, 
            aes(x = flipper_len, y = bill_dep, 
                color = species)) + 
  guides(color = 'none')

p + geom_point(shape = 16, alpha = .5)
p + geom_point(shape = 16, alpha = .5, position = "jitter")

Some points lie exactly on top of other points because data was recorded as integer measurements

Some points lie exactly on top of other points because data was recorded as integer measurements

Jittering the point position allows a visual estimate of how many points overlap.

Jittering the point position allows a visual estimate of how many points overlap.

Statistics

Sometimes, we want to compute statistics based on our data, and map geoms to those computations.

Statistics

Sometimes, we want to compute statistics based on our data, and map geoms to those computations.

Smooth or Trend Line: stat_smooth()

geom_line(aes(x = after_stat(x),     
              y = after_stat(y))) +    
geom_ribbon(    
  aes(x = after_stat(x), 
      ymin = after_stat(ymin), 
      ymax = after_stat(ymax)))

Boxplots (5-number summary): stat_boxplot()

geom_boxplot() 
# A shortcut for something like this:
geom_rect(aes(xmin = x - after_stat(width)/2,
              xmax = x + after_stat(width)/2,
              ymin = after_stat(lower),
              ymax = after_stat(upper)) + 
geom_segment(aes(x = x - after_stat(width)/2,
                 xend = x + after_stat(width)/2,
                 y = after_stat(middle),
                 yend = after_stat(middle))) + 
geom_segment(aes(x = x, xend = xend, 
                 y = after_stat(lower),
                 yend = after_stat(ymin))) + 
geom_segment(aes(x = x, xend = xend, 
                 y = after_stat(upper),
                 yend = after_stat(ymax)))

Statistics

Sometimes, we want to compute statistics based on our data, and map geoms to those computations.

bar plots (count up data by category): stat_count()

geom_bar(aes(x = x, y = after_stat(count)))
# A shortcut for something like this:
geom_rect(aes(xmin = x - after_stat(width),
              xmax = x + after_stat(width),
              ymin = 0,
              ymax = after_stat(count)))

Histograms (cut into bins, then count): stat_bin()

geom_histogram(aes(x = x, y = after_stat(count)))
# A shortcut for something like this:
geom_rect(aes(xmin = after_stat(xstart),
              xmax = after_stat(xend),
              ymin = 0,
              ymax = after_stat(count)))

Frequency Polygons (cut into bins, then count): stat_bin()

geom_freqpoly(aes(x = x, y = after_stat(count)))
# A shortcut for something like this:
geom_line(aes(x = x,
              y = after_stat(count)))

Statistics

Sometimes, we want to compute statistics based on our data, and map geoms to those computations.

density plots: stat_density()

geom_density(aes(x = x, y = after_stat(density)))

# A shortcut for something like this:
geom_line(aes(x = x, y = after_stat(density)))

# Or this (if fill is specified)
geom_ribbon(aes(x = x, ymin = 0, ymax = after_stat(density)))

eCDF (sort, calculate proportion <= each x value): stat_ecdf()

geom_step(aes(x = x, y = after_stat(count)))

# A shortcut for something like this: 
# Vertical piece
geom_segment(aes(x = x_prev,
                 xend = x_prev,
                 y = after_stat(prop_prev),
                 yend = after_stat(prop))) + 
# Horizontal piece
geom_segment(aes(x = x_prev,
                 xend = x,
                 y = after_stat(prop),
                 yend = after_stat(prop)))          

Scales

Scales

By default, ggplot2 chooses reasonable default scales

geom_bar uses scale_x_discrete()

geom_bar uses scale_x_discrete()

geom_histogram and geom_density use scale_x_continuous()

geom_histogram and geom_density use scale_x_continuous()
  • scale_{aesthetic}_{type}
    • aesthetic can be x, y, fill, color, shape, etc.,

Scale Types

  • manual - available for almost all scales
  • position (x, y): continuous, discrete, date, datetime
    • transforms: scale_*_log10, scale_*_reverse, scale_*_sqrt

Color/fill have special scales:

  • discrete: scale_*_brewer, scale_*_grey

tayloRswift has album-themed color palettes.
ggsci has palettes from Futurama, Simsons, StarTrek, Tron, Rick and Morty and various news outlets

Scale Types

Color/fill have special scales:

  • discrete: scale_*_brewer, scale_*_grey
  • continuous: scale_*_distiller (discrete scale interpolated), scale_*_gradient (low to high), scale_*_gradient2 (bidirectional)
    • “trans” argument to add a transformation (log10 is useful)
  • Palette choices:

We’ll talk more about color next time

Coordinate Systems

+ coord_xxx()

  • Cartesian: Standard x and y axis
  • Fixed: Ensure there is a fixed aspect ratio
  • Flip: swap x and y axes
  • Polar: specify which variable (x, y) is the angle (theta)
  • Trans: specify x or y axis transformations

Small Multiples

Subplots (Facets)

When there are too many categorical variables, subplots can help!

ggplot(data = penguins,
       aes(x = body_mass, 
           y = bill_len, 
           color = sex)) + 
  geom_point() + 
  facet_wrap(~species, 
             ncol = 2) +
  guides(color = 'none')

  • facet_wrap() - no ordering

  • facet_grid(rowvar ~ colvar) - align in a grid

  • More about this next time!