Notes Mar 31

Harold Nelson

3/30/2021

library(tidyverse)
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.0 ──
## ✓ ggplot2 3.3.0     ✓ purrr   0.3.4
## ✓ tibble  3.0.5     ✓ dplyr   1.0.3
## ✓ tidyr   1.0.2     ✓ stringr 1.4.0
## ✓ readr   1.3.1     ✓ forcats 0.5.0
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()
library(socviz)
library(RColorBrewer)

I’ll produce part of one of Healy’s graphs and use it as a platform to illustrate color picking.

p0 <- 
  election %>% 
  filter( st != "DC",
          census == "West") %>% 
  ggplot(mapping = aes(x = r_points,
                   y = reorder(state, r_points),
                  color = party))

p1 <- p0 + geom_vline(xintercept = 0, color = "gray30") +
    geom_point(size = 2)

Now use Healy’s party_colors with scale_color_manual() to display the graphic.

party_colors <- c("#2E74C0", "#CB454A")

p1 + scale_color_manual(values = party_colors)

Now pick some different colors. Use the html color picker to give the democrats a green color and paint the republicans black. Note: To get pure black, set everything to 0.

Answer

party_colors <- c("#399B7F", "#000000")

p1 + scale_color_manual(values = party_colors)

Now let’s practice using named colors from Rcolor.pdf. Make the democrats dodgerblue and the republicans firebrick1.

Answer

party_colors <- c("dodgerblue", "firebrick1")

p1 + scale_color_manual(values = party_colors)

Again

Try some different colors.

Answer

party_colors <- c("navyblue", "goldenrod2")

p1 + scale_color_manual(values = party_colors)

Now let’s map color to the variable r_points. First just do the default.

Answer

p0 <- 
  election %>% 
  filter( st != "DC",
          census == "West") %>% 
  ggplot(mapping = aes(x = r_points,
                   y = reorder(state, r_points),
                  color = r_points))

p1 <- p0 + geom_vline(xintercept = 0, color = "gray30") +
    geom_point(size = 2)

p1

Now try to use a color gradient with low set to blue and high set to red.

See https://ggplot2.tidyverse.org/reference/scale_gradient.html

Answer

p1 + scale_color_gradient(low = "blue", high = "red")

Try from orange to purple. Or just pick a few contrasting colors.

Answer

p1 + scale_color_gradient(low = "orange", high = "purple")

Try the same combination with gradient2.

Answer

p1 + scale_color_gradient2(low = "orange", high = "purple")

Try scale_color_viridis_c() with defaults.

Answer

p1 + scale_color_viridis_c()

See https://ggplot2.tidyverse.org/reference/scale_viridis.html

Reverse the direction so that light is low and dark is high.

Answer

p1 + scale_color_viridis_c(direction = -1)

Try the magma option.

Answer

p1 + scale_color_viridis_c(direction = -1,
                           option = "magma")