Harold Nelson
2022-11-06
We will follow Chapter 12 of Winston Chang’s Graphics Cookbook closely.
It is at https://r-graphics.org/chapter-colors.
Get the packages we need.
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.2 ──
## ✔ ggplot2 3.3.6 ✔ purrr 0.3.4
## ✔ tibble 3.1.8 ✔ dplyr 1.0.10
## ✔ tidyr 1.2.1 ✔ stringr 1.4.1
## ✔ readr 2.1.2 ✔ forcats 0.5.2
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag() masks stats::lag()
## Loading required package: viridisLite
We can use the builtin dataframe mtcars for a simple example.
Do a scatterplot with disp on the x-axis and mpg on the y-axis. Use the aesthetic color to capture the vehicle weight, wt. Save this graphic as an object p and display it.
In this case, points are solid objects and the appropriate aesthetic is “color” instead of fill. The variable wt is continuous, so we get a continuous scale of blues.
Let’s try viridis_c with defaults.
Set the direction parameter to -1 in the call to viridis so that darker colors will be associated with higher values.
Viridis has different color schemes available. You can get to them with the option parameter in the call to viridis_c(). Potential values are “A” through “H”.
Try a few.
We can use scale_color_gradient(). We need to pick two colors to represent the low and high values. Here’s an example.
Try a few alternatives for named colors using the link to “Named Colors in R” in Moodle.
Let’s use the HTML color picker link in R to designate our low and high colors with hex codes.
For this example we can use a sample of the rows in cdc2. First, we need to get the data.
## 'data.frame': 150 obs. of 15 variables:
## $ genhlth : Factor w/ 5 levels "excellent","very good",..: 1 3 2 4 1 1 5 1 2 3 ...
## $ exerany : num 1 1 0 0 1 1 0 1 1 1 ...
## $ hlthplan : num 1 1 1 1 1 1 1 1 1 0 ...
## $ smoke100 : num 1 0 1 1 0 0 1 0 0 1 ...
## $ height : num 70 65 72 72 70 67 73 73 69 71 ...
## $ weight : int 140 127 200 180 190 165 170 175 210 235 ...
## $ wtdesire : int 140 125 185 180 170 155 170 190 210 205 ...
## $ age : int 35 32 48 37 55 39 42 35 45 42 ...
## $ gender : Factor w/ 2 levels "m","f": 2 2 1 1 1 1 1 1 1 1 ...
## $ BMI : num 20.1 21.1 27.1 24.4 27.3 ...
## $ BMIDes : num 20.1 20.8 25.1 24.4 24.4 ...
## $ DesActRatio: num 1 0.984 0.925 1 0.895 ...
## $ BMICat : Factor w/ 5 levels "Underweight",..: 2 2 3 2 3 3 2 2 4 4 ...
## $ BMIDesCat : Factor w/ 5 levels "Underweight",..: 2 2 3 2 2 2 2 3 4 3 ...
## $ ageCat : Factor w/ 4 levels "18-31","32-43",..: 2 2 3 2 3 2 2 2 3 2 ...
Do a scatterplot of height and weight and use ageCat as our categorical variable. First, we’ll use the default colors.
## ColorBrewer
Now add a color scale from RColorBrewer. Use the YlOrRd palette.