Adjusting axes

Author

Jeffrey R. Stevens

Published

April 24, 2023

  1. Using the mpg data, create boxplots of highway fuel efficiency as a function of class.
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
mpg |> 
  ggplot(aes(x = class, y = hwy)) +
  geom_boxplot()

  1. Zoom into the plot with y-axis limits of 15 and 40 without altering the data.
mpg |> 
  ggplot(aes(x = class, y = hwy)) +
  geom_boxplot() +
  coord_cartesian(ylim = c(15, 40))

  1. Change the y-axis limits to 15 and 40 but allow the statistical transformations to change the data.
mpg |> 
  ggplot(aes(x = class, y = hwy)) +
  geom_boxplot() +
  ylim(15, 40)
Warning: Removed 10 rows containing non-finite outside the scale range
(`stat_boxplot()`).

  1. Replot #1 but using a log10 scale.
mpg |> 
  ggplot(aes(x = class, y = hwy)) +
  geom_boxplot() +
  scale_y_log10()

  1. Replot #1 but with y-axis limits running from 0 to 50 and with labels in increments of 5 but no minor grid lines.
mpg |> 
  ggplot(aes(x = class, y = hwy)) +
  geom_boxplot() +
  scale_y_continuous(limits = c(0, 50), breaks = seq(0, 50, 5)) +
  theme(panel.grid.minor = element_blank())

  1. Replot #1 but create separate panels based on year (as rows) and cylinders (as columns) and allowing the scales to vary across rows.
mpg |> 
  ggplot(aes(x = class, y = hwy)) +
  geom_boxplot() +
  facet_grid(rows = vars(year), cols = vars(cyl), scale = "free")

  1. Replot #1 and assign it to hwy_plot and replot a similar version with city fuel efficiency named cty_plot. Then combine them into a compound plot labeled as subfigures A and B and save this figure on your computer as a PNG file.
hwy_plot <- mpg |> 
  ggplot(aes(x = class, y = hwy)) +
  geom_boxplot()
cty_plot <- mpg |> 
  ggplot(aes(x = class, y = cty)) +
  geom_boxplot()
library(patchwork)
hwy_plot + cty_plot + plot_annotation(tag_levels = "A")

# ggsave("fuel_efficiency_class.png")