Color Palettes: Moving Beyond ggplot2 Defaults
Colors are one of the most powerful tools to tell a story with your data. In this lesson, you’ll use color to highlight patterns, reinforce categories, and make your plots more readable — all while moving beyondggplot2’s default palettes.
You’ll explore built-in palettes, learn to tweak scales for impact, and discover popular community palettes likeviridis and RColorBrewer. Along the way, you’ll also see how to craft custom palettes, giving you full flexibility without getting lost in options.
🧞♂️ The Magic (and Limits) of Defaults
When we covered the foundations of ggplot2, you saw how you map color and fill to your data and that each aesthetic has a corresponding scale function.
Mapping variables to color or fill aesthetics tells ggplot2 what to color. It will then apply a default scale_* palette based on the type of your variable and the aesthetic. The scale functions defining which colors to use start with scale_color_* or scale_fill_*.
🪄 How ggplot Distinguishes Groups
Let’s start by mapping color to a categorical variable using the dataset.
If we plot bill length versus bill depth and map a categorical variable like species (a column of type character) to color, the clusters become immediately visible:
ggplot2 applies the viridis palette. Pass factor(species, ordered = TRUE) to color to give it a try!Here, ggplot2 invisibly adds scale_color_discrete(). The default qualitative palette for categorical variables is technically fine — but the defaults are not very flexible or visually inspiring.
- Limited control — you can’t easily highlight one group or adjust hues to match a style guide.
- Consistency across plots — reordering factors or adding new levels can change which colors are assigned.
- Design polish — the defaults are safe, but often look generic and uninspired.
🪄 How ggplot Represents Values
Try changing the mapping to a numeric variable instead — for example, replace species with body_mass_g in the code above. Now, ggplot2 applies the well-known blue gradient to encode the values sequentially.
Oh no! 😱
It seems like you haven’t enrolled in the course yet!
Join many other students today and become the ggplot2 expert your company needs!
Or Login