Color

Author

Jeffrey R. Stevens

Published

April 7, 2023

  1. Using the mtcars data, create a scatterplot of the fuel efficiency as a function of weight with color based on the number of cylinders.
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 |> 
  mutate(cyl = as.factor(cyl)) |> 
  ggplot(aes(x = wt, y = mpg, color = cyl)) +
  geom_point()

  1. Repeat the scatterplot but use scale_color_brewer() to set the palette to Set1.
mtcars |> 
  mutate(cyl = as.factor(cyl)) |> 
  ggplot(aes(x = wt, y = mpg, color = cyl)) +
  geom_point() +
  scale_color_brewer(palette = "Set1")

  1. Why did you use scale_color_brewer() not scale_fill_brewer() or scale_color_distiller()?

  2. Repeat scatterplot #1 but use scale_color_manual() to set the three colors to red, green, and blue.

mtcars |> 
  mutate(cyl = as.factor(cyl)) |> 
  ggplot(aes(x = wt, y = mpg, color = cyl)) +
  geom_point() +
  scale_color_manual(values = c("red", "green", "blue"))

  1. Find three colors (either names or hex codes), and repeat scatterplot #4 with your own colors.
mtcars |> 
  mutate(cyl = as.factor(cyl)) |> 
  ggplot(aes(x = wt, y = mpg, color = cyl)) +
  geom_point() +
  scale_color_manual(values = c("coral2", "palegreen4", "slateblue4"))

  1. Using the mtcars data, create a scatterplot of the fuel efficiency as a function of weight with color based on horsepower using the BuPu palette and reverse the direction of the gradient.
mtcars |> 
  ggplot(aes(x = wt, y = mpg, color = hp)) +
  geom_point() +
  scale_color_distiller(palette = "BuPu", direction = 2)

  1. Create a new column in mtcars that centers and scales displacement with the scale() function. Create a scatterplot of fuel efficiency as a function of weight with color based on the rescaled displacement, using a diverging scale of your choice.
mtcars |> 
  mutate(disp2 = scale(disp)) |> 
  ggplot(aes(x = wt, y = mpg, color = disp2)) +
  geom_point() +
  scale_color_distiller(palette = "RdBu")