Visualize Data

Your Turn 0

Add a setup chunk that loads the tidyverse packages and turn the global option eval to true in the above YAML header.

mpg

Your Turn 1

Run the code on the slide to make a graph. Pay strict attention to spelling, capitalization, and parentheses!

Your Turn 2

Add color, size, alpha, and shape aesthetics to your graph. Experiment.

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

Help Me

What do facet_grid() and facet_wrap() do? (run the code, interpret, convince your group)

# Makes a plot that the commands below will modify
q <- ggplot(mpg) + geom_point(aes(x = displ, y = hwy))

q + facet_grid(cols = vars(cyl))
q + facet_grid(rows = vars(drv))
q + facet_grid(rows = vars(drv), cols = vars(cyl))
q + facet_wrap(facets = vars(class))

Your Turn 3

Add the black code to your graph. What does it do?

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

Your Turn 4

Replace this scatterplot with one that draws boxplots. Use the cheatsheet. Try your best guess.

ggplot(mpg) + geom_point(aes(class, hwy))

Your Turn 5

Make a histogram of the hwy variable from mpg. Hint: do not supply a y variable.

Your Turn 6

Use the help page for geom_histogram to make the bins 2 units wide.

Your Turn 7

Make a bar chart class colored by class. Use the help page for geom_bar to choose a “color” aesthetic for class.

Quiz

What will this code do?

ggplot(mpg) + 
  geom_point(aes(displ, hwy)) +
  geom_smooth(aes(displ, hwy))

Quiz

What is different about this plot? Run the code!

p <- ggplot(mpg) + 
  geom_point(aes(displ, hwy)) +
  geom_smooth(aes(displ, hwy))

library(plotly)
ggplotly(p)

Take aways

You can use this code template to make thousands of graphs with ggplot2.

ggplot(data = <DATA>) +
  <GEOM_FUNCTION>(mapping = aes(<MAPPINGS>))