Visualize Data in R with ggplot2

Exercises

Author
Affiliations
John R Little

Duke University

Published

January 6, 2023

Abstract
These exercises are adapted in whole or in part based on the Master the Tidyverse work by Garrett Grolemund at RStudio.
CC BY Garrett Grolemund, RStudio ; BY-NC John Little
CC BY-NC 4.0

These exercises support your learning after watching the instructional video

library(tidyverse)

The dataset, mpg, is an onboard dataset, part of the ggplot2 package. You can learn more about it by searching the help tab for “mpg”, or type ?mpg in the console.

mpg

Your Turn 1

IN THE code-chunk, below, manually type the following code:

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

Pay strict attention to spelling, capitalization, and parentheses! Try not to copy and paste, just this once.

Your Turn 2

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

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

Your Turn 3

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

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

Your Turn 4

Make a histogram of the hwy variable from mpg.

Your Turn 5

Make a density plot of hwy colored by class.

Your Turn 6

Make a bar chart hwy colored by class.

Your Turn 7

Predict what this code will do. Then run it.

mpg %>% 
  ggplot() + 
  geom_point(aes(displ, hwy)) +
  geom_smooth(aes(displ, hwy))
`geom_smooth()` using method = 'loess' and formula = 'y ~ x'

Your Turn 8

Save the last plot

ggsave(_____)
# or right-click the image