SyntaxStudy
Sign Up
R Introduction to ggplot2 and the Grammar of Graphics
R Beginner 2 min read

Introduction to ggplot2 and the Grammar of Graphics

ggplot2 is R's most popular data visualisation package, created by Hadley Wickham and based on Leland Wilkinson's Grammar of Graphics. The core idea is that every plot is built from the same set of components: a dataset, a set of aesthetic mappings (aes()) that link data columns to visual properties, and at least one geometric object (geom_*) that determines the type of mark drawn. Additional components like scales, coordinate systems, facets, and themes refine the appearance without changing the underlying data mapping. The ggplot() function initialises a plot object, and you add layers to it using the + operator. This compositional approach means a complete plot is a description of its components rather than an imperative sequence of drawing commands. The aesthetic mappings inside aes() connect data variables to visual channels such as x position, y position, colour, fill, size, shape, and alpha transparency. Mappings defined in the top-level ggplot() call are inherited by all layers; mappings defined inside a specific geom override the defaults for that layer. Understanding the distinction between aesthetic mappings and aesthetic constants is crucial. When a visual property depends on data (e.g., colour by species), it goes inside aes(). When it is a fixed value applied uniformly (e.g., all points in red), it goes outside aes() as an argument to the geom. Confusing these two is the single most common ggplot2 mistake for newcomers.
Example
library(ggplot2)

# Built-in dataset
data(mpg)   # fuel economy data for 234 cars

# Minimal plot: just axes, no geom yet
ggplot(mpg, aes(x = displ, y = hwy))

# Scatter plot
ggplot(mpg, aes(x = displ, y = hwy)) +
    geom_point()

# Map colour to a categorical variable (inside aes)
ggplot(mpg, aes(x = displ, y = hwy, colour = class)) +
    geom_point()

# Fixed colour constant (outside aes)
ggplot(mpg, aes(x = displ, y = hwy)) +
    geom_point(colour = "steelblue", size = 2, alpha = 0.7)

# Add a smooth trend line
ggplot(mpg, aes(x = displ, y = hwy)) +
    geom_point(alpha = 0.4) +
    geom_smooth(method = "lm", se = TRUE)

# Map multiple aesthetics
ggplot(mpg, aes(x = displ, y = hwy,
                colour = class, size = cyl)) +
    geom_point(alpha = 0.6)

# Labels and title
ggplot(mpg, aes(x = displ, y = hwy, colour = drv)) +
    geom_point() +
    labs(
        title    = "Engine Displacement vs Highway MPG",
        subtitle = "By drive type",
        x        = "Displacement (litres)",
        y        = "Highway MPG",
        colour   = "Drive type"
    )