Grammar of graphics I

Author

Jeffrey R. Stevens

Published

March 31, 2023

  1. Using the mtcars data, create a scatterplot of the fuel efficiency as a function of weight.
library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.1.4     ✔ readr     2.1.5
✔ forcats   1.0.0     ✔ stringr   1.5.1
✔ ggplot2   3.5.0     ✔ tibble    3.2.1
✔ lubridate 1.9.3     ✔ tidyr     1.3.1
✔ purrr     1.0.2     
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
mtcars |> 
  ggplot(aes(x = wt, y = mpg)) +
  geom_point()

  1. Repeat the plot but only with vehicles having 4 or 6 cylinders.
mtcars |> 
  filter(cyl < 8) |> 
  ggplot(aes(x = wt, y = mpg)) +
  geom_point()

  1. Repeat plot #1 but add a smooth line underneath the data points.
mtcars |> 
  ggplot(aes(x = wt, y = mpg)) +
  geom_smooth() +
  geom_point()
`geom_smooth()` using method = 'loess' and formula = 'y ~ x'

  1. Make a boxplot of fuel efficiency for each cylinder size.
mtcars |> 
  mutate(cyl = as.factor(cyl)) |> 
  ggplot(aes(x = cyl, y = mpg)) +
  geom_boxplot()

  1. Add ” cylinders” to the end of each value in the cylinder column of data and replot #4.
mtcars |> 
  mutate(cyl = paste0(cyl, " cylinders")) |> 
  ggplot(aes(x = cyl, y = mpg)) +
  geom_boxplot()

  1. Replot #4 ordering the cylinders such that the median mpg increases from left to right.
mtcars |> 
  mutate(cyl = as.factor(cyl)) |> 
  ggplot(aes(x = fct_reorder(cyl, mpg), y = mpg)) +
  geom_boxplot()