Statistical Transformations
You'll learn how ggplot2 computes summary statistics behind the scenes before drawing your plots.
The Hidden Math Behind Your Visuals
When you create a histogram in ggplot2, you don't manually count how many observations fall into each bin—ggplot2 does that for you. When you add a smoothed trend line, you don't calculate the moving average yourself—ggplot2 handles it. These automatic calculations are called statistical transformations (or "stats").
Every geom in ggplot2 has a default stat that runs before the geometry is drawn. Sometimes the stat is "identity" (meaning "use the data as-is"), but often it's doing real work:
- Histograms use
stat_bin()to count observations in ranges - Smooth lines use
stat_smooth()to fit regression or loess curves - Box plots use
stat_boxplot()to calculate quartiles and outliers - Bar charts can use
stat_count()to tally categories
Think of stats as a preprocessing step: raw data goes in, transformed summary data comes out, and then the geom draws it.
Why This Matters
Understanding stats helps you:
- Know what ggplot2 is calculating automatically
- Override defaults when needed (e.g., use pre-counted data with
stat = "identity") - Create custom summaries by swapping stats
You can even call stats directly (stat_summary(), stat_bin()) without specifying a geom, giving you control over the transformation layer independently.
Key Takeaway: Statistical transformations are ggplot2's way of computing summaries like counts, bins, and smoothed values before rendering geometries—every geom has a default stat, and you can override or customize it to fit your needs.