Gain familiarity with the way that color palettes and aesthetic themes are specified in
ggplot2, so that you can use both in your own visualizations.
The examples will use the
storms dataset which is included in the
dplyr package (both
ggplot2 are loaded by
tidyverse, so it suffices to do
library(tidyverse)). The data comes from the NOAA Atlantic hurricane database, and includes positions and attributes of 198 tropical storms measured at six hour intervals during each storm’s lifetime.
stormsdata, and examine the documentation using the
?datasetnamesyntax to see the definitions of the variables.
You might notice that in the boxplot you get, the storm types are ordered alphabetically. In this case the types have a natural ordering based on their intensity: tropical depressions are the least severe, and hurricanes the most. Our plot will be more natural if we respect this natural ordering. We can do this as follows:
We can add some color to the plot by adding a redundant mapping: in addition to mapping
status to the
x dimension, we’ll also map it to the
fill feature (the interior color of the boxplots).
The default color palette looks pretty nice, but just for fun let’s see how we could change it.
One option is to directly specify the colors we want R to use, using hexadecimal codes for the colors’ RGB values. The colors in the following example come from one of my personal favorite palettes (you might recognize it from my website, for example), the Solarized palette by Ethan Schoonover. In each code, the first two characters represent the red channel (on a 0-255 scale, encoded in base 16), the next two represent the green channel, and the last two represent the blue channel.
Manually specifying colors allows very precise control, but it’s tedious, time consuming, and brittle. It is generally better and easier to use predefined color palettes instead.
A fairly large and diverse collection of color palettes was developed by Cynthia Brewer (link) and is available in the
After loading the package, we can view the included palettes with