Color Scales and Palettes
You'll learn how to apply and customize color scales in ggplot2 using built-in and custom palettes.
Color scales control how your data values map to actual colors on the plot. While you've already learned about color concepts and types of palettes, now you'll apply them directly using ggplot2's scale functions.
Core Idea
Think of color scales as translators between your data and visual output. Your dataset might have categories like "Product A, B, C" or continuous values like temperatures from 0-100. Color scales determine which specific colors represent each category or value range.
Main Color Scale Functions
scale_color_manual() gives you complete control—you specify exactly which colors to use:
ggplot(data, aes(x = x_var, y = y_var, color = category)) +
geom_point() +
scale_color_manual(values = c("red", "blue", "green"))
ColorBrewer palettes offer scientifically-designed color schemes for categorical, sequential, or diverging data:
scale_color_brewer(palette = "Set1") # for categories
scale_fill_brewer(palette = "Blues") # for sequential data
Viridis palettes are perceptually uniform and colorblind-friendly:
scale_color_viridis_d() # discrete (categorical)
scale_color_viridis_c() # continuous
Custom Palettes
Create your own palette vector and feed it to scale_color_manual():
my_palette <- c("#FF6B6B", "#4ECDC4", "#45B7D1")
scale_color_manual(values = my_palette)
You can also adjust transparency, gradients, and binning behavior within these scale functions.
Key Takeaway: Color scales bridge your data to visual colors—use scale_color_manual() for full control, ColorBrewer for proven schemes, viridis for accessibility, or build custom palettes for brand-specific needs.