पाठ 13 / 25
The Grammar of Graphics with ggplot2
Build plots from data, aesthetics and geoms with ggplot2.
Plots built in layers
ggplot2 implements the grammar of graphics: every plot combines data, aesthetic mappings (aes()) that connect variables to visual properties such as x, y, colour, size and fill, and geoms (geometric objects) that draw them: geom_point() for scatter plots, geom_line() for trends, geom_col() for bars with given heights, geom_bar() to count rows, geom_histogram() and geom_density() for distributions, geom_boxplot() for comparing groups, and geom_smooth() for trend lines. You build a plot by adding layers with +. Mappings inside aes() depend on data (colour = city), while settings outside aes() are fixed (colour = "steelblue"). Statistical transformations, scales and coordinate systems are further layers. The same small vocabulary produces almost any statistical chart, and plots are objects you can store, modify and save with ggsave().
Layers of a ggplot
Data, aesthetic mappings and geoms stack up into a complete plot.
Three common plots
Scatter with trend, grouped bars and a distribution.
library(ggplot2)
library(dplyr)
# scatter plot with a trend line per city
ggplot(sales, aes(x = order_date, y = amount_inr, colour = city)) +
geom_point(alpha = 0.5) +
geom_smooth(method = "loess", se = FALSE)
# revenue per city as bars
sales |>
summarise(revenue = sum(amount_inr), .by = city) |>
ggplot(aes(x = reorder(city, revenue), y = revenue)) +
geom_col(fill = "steelblue") +
coord_flip()
# distribution of order values, log scale for skewed money data
ggplot(sales, aes(x = amount_inr)) +
geom_histogram(bins = 30) +
scale_x_log10()
ggsave("figures/order_values.png", width = 7, height = 4, dpi = 300)Inside or outside aes?
aes(colour = "blue") maps a constant string as if it were data, giving a legend called "blue" and an unexpected colour. Set fixed colours outside aes(): geom_point(colour = "blue").
त्वरित जाँच: In ggplot2, what does aes() define?
- Mappings from data variables to visual properties such as x, y and colour
- The file format of the plot
- The theme only
- The number of bins
Answer
Mappings from data variables to visual properties such as x, y and colour — Aesthetic mappings connect data columns to visual channels.