Aesthetic Mappings: Global vs Layer-Specific
You'll learn how to control whether aesthetic mappings apply to all layers or just specific geoms in your ggplot2 visualizations.
When building layered plots in ggplot2, you face a key decision: where do you define your aesthetic mappings (aes())? This choice determines which geoms inherit those mappings and which remain independent.
Global Aesthetics: Shared Across All Layers
Aesthetics defined inside the initial ggplot() function are global—they apply to every geom layer you add afterward. Think of this as setting house rules that everyone follows.
When you write ggplot(data, aes(x = var1, y = var2, color = category)), every subsequent geom_point(), geom_line(), or other geom automatically uses those x, y, and color mappings unless you override them.
Layer-Specific Aesthetics: Local Control
Aesthetics defined inside individual geom_*() functions are layer-specific—they only affect that particular geom. This is like giving special instructions to one person while others follow the house rules.
For example, you might set global x and y mappings in ggplot(), but add geom_point(aes(size = another_var)) to size points by a variable that doesn't affect other layers.
When to Use Which?
Use global aesthetics when multiple layers share the same mappings (common for x and y axes). Use layer-specific aesthetics when you want different geoms to visualize different aspects of your data, or when layering datasets that require distinct mappings.
Layer-specific mappings also override global ones when both exist—the local definition wins.
Key Takeaway: Global aesthetics in ggplot() are inherited by all layers, while layer-specific aesthetics in geom_*() functions apply only to that geom, giving you precise control over which mappings affect which visual elements.