Statistical Transformations with stat_* Layers
What you'll learn: How to apply built-in statistical summaries like smoothing, binning, and density estimation directly within your ggplot2 layers.
The Core Idea
In ggplot2, statistical transformations compute summaries or modifications of your raw data before plotting. While geom_* functions focus on how to draw, stat_* functions focus on what calculations to perform first. You can add these transformations as layers to reveal patterns that aren't immediately visible in raw data.
Think of it like a chef preparing ingredients: your raw data is like fresh vegetables, but stat_* layers are the prep work—dicing, marinating, reducing—that transforms them into something more refined before plating (rendering the geom).
How It Works
Every geom_* has a default stat_* partner working behind the scenes. For example, geom_histogram() uses stat_bin() to count values in ranges. You can explicitly use stat_* functions to:
- Smooth trends:
stat_smooth()fits regression lines or curves - Estimate densities:
stat_density()creates smooth distribution curves - Bin data:
stat_bin()aggregates continuous data into intervals - Compute summaries:
stat_summary()calculates means, medians, or custom functions
You add these transformations just like geometric layers, and they automatically compute and visualize the results.
# Example structure (conceptual - based on prior knowledge)
ggplot(data, aes(x = variable)) +
stat_density(geom = "line") # Computes density, draws as line
The beauty is separation of concerns: the statistical calculation is independent of how you choose to visualize it.
When to Use Them
Use stat_* layers when you need to visualize computed properties rather than raw values—trends in noisy data, distribution shapes, or aggregated summaries.
Key Takeaway: stat_* layers transform your raw data into statistical summaries (smoothing, binning, density) directly within your plot, separating what to compute from how to draw it.