lecture08

Recap?

Today’s class

  • What is ggplot() and why is it awesome?

  • Think of a plot / graph as having multiple layers

  • ..

Building a plot layer by layer

Overview of the ggplot() syntax

Source: blog/sharpsightlabs.com:

Geom layers

types of geoms

Source: blog/sharpsightlabs.com:

There’s many more geoms in the ggplot cheatsheet!

Let us quickly see an animation of empty plot, adding axes, adding data for the histogram

Empty plot: ggplot() call

library(tidyverse)
data("mtcars")

ggplot(data = mtcars)

Adding axes: mapping = aes()

ggplot(data = mtcars,
       mapping = aes(x = cyl, y = mpg))

Adding points: geom_point()

ggplot(data = mtcars,
       mapping = aes(x = cyl, y = mpg)) + 
  geom_point()

Adding line: geom_line()

ggplot(data = mtcars,
       mapping = aes(x = cyl, y = mpg)) + 
  geom_point() + 
  geom_line()

Assign the plot to a variable

This hides the plot and needs to be called with print()

base_plt <- 
  ggplot(data = mtcars,
       mapping = aes(x = cyl, y = mpg)) + 
  geom_point() + 
  geom_line()

Hey, where’s my plot gone? 🤔

Call the plot object to display/ print it

base_plt

Add some colour = col_name in aes()

colour_plt <- # assign and print plot at the same
  ggplot(data = mtcars %>% mutate(vs_factor = as_factor(vs)),
       mapping = aes(x = cyl, y = mpg, colour = vs_factor)) + 
  geom_point() + geom_line() 

Make a constant colour = 'red' - Doesn’t work

ggplot(data = mtcars %>% mutate(vs_factor = as_factor(vs)),
       mapping = aes(x = cyl, y = mpg, colour = 'dracula')) + 
  geom_point() + geom_line() 

Did the colour = 'red' really work?

ggplot(data = mtcars %>% mutate(vs_factor = as_factor(vs)),
       mapping = aes(x = cyl, y = mpg, colour = 'blue')) + 
  geom_point() + geom_line() 

Make a constant colour = 'red' outside aes()

Hint: There should be no legend!

ggplot(data = mtcars,
       mapping = aes(x = cyl, y = mpg)) +
  
  geom_point(colour = 'blue') + geom_line(colour = 'blue') 

Styling your ggplot

How to train your ggplot::

Making axis labels great again

colour_plt + 
  labs(
    x = 'number of cylinders', y = 'miles per gallon',
    title = "What's the takeaway here?",
    subtitle = 'More cylinders => less miles per gallon'
  )

Add text annotations on the plot

colour_plt + 
  annotate(geom = 'text', 
           x = 6, y = 25, colour = 'darkgreen',
           label = 'this is interesting, eh!?')

Make broad style changes based on theme

colour_plt + theme_minimal()

Onto the worksheet now

Please download the _class8_ggplot_worksheet.Rmd or the .R file with the same name from the syllabus website

  • the .Rmd will make it easier to read the prompts and run code by clicking on the “play” button (run current chunk) for each chunk

  • If you are not comfortable with this, you can use the .R file instead with the same content

Design principles for graphics

coming later..?