2024

load the ggplot2 package

library(ggplot2)

Overview of scales

  • Color and Fill: For mapping numeric data to gradients of colors.
    • scale_color_gradient(), scale_fill_gradient(): Gradient (two colors).
    • scale_color_gradient2(), scale_fill_gradient2(): Diverging gradient (three colors).
    • scale_color_gradientn(), scale_fill_gradientn(): Gradient of n colors.
  • Position: For continuous position scales (x and y axes).
    • scale_x_continuous(), scale_y_continuous(): Default continuous position scales.
    • scale_x_log10(), scale_y_log10(): Logarithmic scales.
    • scale_x_sqrt(), scale_y_sqrt(): Square root scales.
    • scale_x_reverse(), scale_y_reverse(): Reverse scales.
  • Color and Fill: For mapping discrete variables to colors.
    • scale_color_hue(), scale_fill_hue(): Default discrete color scale.
    • scale_color_brewer(), scale_fill_brewer(): Color scales from the ColorBrewer palettes.
    • scale_color_manual(), scale_fill_manual(): Manual color scales to specify custom colors.
    • scale_color_viridis_d(), scale_fill_viridis_d(): Discrete scales using the viridis color palette.
  • Shape: For mapping discrete variables to shapes.
    • scale_shape(): Default shape scale.
    • scale_shape_manual(): Manual shape scales to specify custom shapes.
  • Position: For date and datetime data.
    • scale_x_date(), scale_y_date(): Date scales for the x or y axis.
    • scale_x_datetime(), scale_y_datetime(): DateTime scales for the x or y axis.
    • scale_x_time(), scale_y_time(): Time scales (without dates).
  • Size: For mapping variables to sizes.
    • scale_size(): Continuous data to size.
    • scale_size_manual(): Manual size mapping.
    • scale_size_area(): Proportional area scales.
  • Alpha: For mapping variables to transparency levels.
    • scale_alpha(): Continuous data to alpha (transparency).
    • scale_alpha_manual(): Manual alpha scales.

Continuous Scales: Color Gradient

# Use `scale_color_gradient()` to map numeric data to a two-color gradient.
library(ggplot2)
ggplot(mpg, aes(x = displ, y = hwy, color = cyl)) + 
  geom_point() + 
  scale_color_gradient(low = "blue", high = "red")

Continuous Scales: Logarithmic Transformation

# Apply a logarithmic transformation to an axis with `scale_y_log10()`.
ggplot(mpg, aes(x = displ, y = hwy)) + 
  geom_point() + 
  scale_y_log10()

Discrete Scales: Color Brewer

# Use `scale_color_brewer()` for discrete variables, utilizing ColorBrewer palettes.
ggplot(mpg, aes(x = displ, y = hwy, color = class)) + 
  geom_point() + 
  scale_color_brewer(palette = "Set1")

Discrete Scales: Manual Color

# Manually set colors for discrete variables with `scale_color_manual()`.
ggplot(mpg, aes(x = displ, y = hwy, color = class)) + 
  geom_point() + 
  scale_color_manual(values = c("compact" = "blue", "suv" =
                                "red", "2seater" = "green"))