ggplot2 is R's signature plotting library, built on the Grammar of Graphics. Once you internalise the grammar — data + aesthetics + geom + scales + themes — you can build virtually any chart with a small consistent vocabulary.
The grammar
library(ggplot2)ggplot(bankrates, aes(x = month, y = lending_rate)) +geom_line() +labs(title = "Kenyan lending rates", y = "Rate (%)")
Every ggplot has at minimum: data (the data frame), an aes mapping (which columns control which visual properties), and one or more geoms (the geometric shapes — point, line, bar, etc.). You add layers with +.
Common geoms
- geom_point — scatter plot
- geom_line — line plot
- geom_bar — bar plot (counts)
- geom_col — bar plot (values)
- geom_histogram — histogram
- geom_boxplot — boxplot
- geom_smooth — fitted regression curve with CI
Aesthetics in detail
ggplot(bankrates, aes(x = month, y = lending_rate, colour = bank)) +geom_line()# colour = bank means draw a separate line per bank, with auto-legend
Faceting — small multiples
ggplot(bankrates_long, aes(x = month, y = rate)) +geom_line() +facet_wrap(~ bank, scales = "free_y")# One panel per bank, each with its own y-axis scale
Scales and themes
ggplot(bankrates, aes(x = month, y = lending_rate)) +geom_line() +scale_y_continuous(labels = scales::percent) +theme_minimal() +labs(title = "Lending rates", x = NULL, y = "Rate")
Plot in long format
ggplot expects long data. If you have wide data, pivot_longer first. Trying to draw multiple lines from wide data is the most common ggplot frustration for beginners.
Exercise
Plot a line chart of bankrates with month on x and lending_rate on y.