SyntaxStudy
Sign Up
R Scales, Themes, and Customisation
R Beginner 1 min read

Scales, Themes, and Customisation

Scales control the mapping between data values and the visual range of an aesthetic. Every aesthetic automatically gets a default scale, but you can override it with a scale_*() function. For example, scale_colour_manual() lets you specify exact colours, scale_colour_brewer() uses pre-built ColorBrewer palettes, and scale_colour_gradient() creates a two-colour gradient for continuous data. Axis scales are controlled with scale_x_continuous(), scale_x_log10(), scale_x_date(), and so on, allowing you to set limits, breaks, labels, and transformations. The theme system controls all non-data elements: background colour, grid lines, axis text, legend position, title font size, and so on. ggplot2 ships with several complete themes — theme_bw(), theme_minimal(), theme_classic(), theme_void() — that provide a consistent base style. Individual elements are overridden with theme() using element_text(), element_line(), element_rect(), or element_blank() to remove them entirely. The ggthemes and hrbrthemes packages provide additional professionally designed themes. Saving plots is done with ggsave(), which infers the file format from the extension and accepts width, height, and dpi arguments. ggplot2 also integrates with the patchwork package for combining multiple independent plots into a single figure with shared legends, aligned axes, and annotated panels — an essential tool for scientific publications and dashboards.
Example
library(ggplot2)
data(mpg)

# Manual colour scale
ggplot(mpg, aes(x = displ, y = hwy, colour = drv)) +
    geom_point(size = 2) +
    scale_colour_manual(
        values = c("4" = "#E41A1C", "f" = "#377EB8", "r" = "#4DAF4A"),
        labels = c("4" = "Four-wheel", "f" = "Front", "r" = "Rear")
    )

# Log scale on x axis
ggplot(diamonds, aes(x = carat, y = price)) +
    geom_point(alpha = 0.1) +
    scale_x_log10() +
    scale_y_log10(labels = scales::comma) +
    labs(title = "Diamond price vs carat (log-log)")

# Continuous colour gradient
ggplot(mpg, aes(x = displ, y = hwy, colour = cty)) +
    geom_point(size = 2) +
    scale_colour_gradient(low = "yellow", high = "red") +
    labs(colour = "City MPG")

# Axis breaks and limits
ggplot(mpg, aes(x = displ, y = hwy)) +
    geom_point() +
    scale_x_continuous(limits = c(1, 7),
                       breaks = seq(1, 7, by = 1)) +
    scale_y_continuous(limits = c(10, 50))

# theme_minimal and manual theme tweaks
p <- ggplot(mpg, aes(x = class)) +
    geom_bar(fill = "steelblue") +
    theme_minimal() +
    theme(
        plot.title   = element_text(size = 16, face = "bold"),
        axis.text.x  = element_text(angle = 45, hjust = 1),
        panel.grid.major.x = element_blank(),
        legend.position    = "bottom"
    ) +
    labs(title = "Styled bar chart")
print(p)

# Saving a plot
# ggsave("my_plot.png", plot = p, width = 8, height = 5, dpi = 300)