R
Beginner
2 min read
Introduction to ggplot2 and the Grammar of Graphics
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"
)