A Detailed Look at Grammar of Graphics

EE BIOL C177/C234

Chuliang Song

Today’s Menu 🎯

  1. Aesthetic mappings β€” inside vs outside aes()
  2. Geometric objects β€” geom_*() functions
  3. Global vs local organization

Aesthetic Mappings

Inside vs Outside aes()

❌ Inside aes() β€” wrong for fixed values

Creates a legend with β€œblue” as a label!

βœ… Outside aes() β€” correct for fixed values

All points become blue

Another Example: size

βœ… Inside aes() β€” map a variable

Size varies by body mass

βœ… Outside aes() β€” set a fixed value

All points are the same size

The Rule

Inside aes() = map a variable from your data

Outside aes() = set a fixed value for all points

Common Aesthetics

Aesthetic Description Example
x, y Position aes(x = bill_length_mm)
color Color aes(color = species)
shape Point shape aes(shape = island)
size Point size aes(size = body_mass_g)
alpha Transparency alpha = 0.5

Combining Aesthetics

Exercise

Fix the aesthetic mapping error:

Geometric Objects

Same Data, Different Geom

Layering Geoms

Order matters β€” last layer is on top!

Global vs Local

Global Aesthetics

Defined in ggplot() β†’ apply to all layers

Local Aesthetics

Defined in geom_*() β†’ apply to that layer only

Best Practice

  • Put shared aesthetics in ggplot()
  • Put layer-specific aesthetics in geom_*()
  • When unsure β†’ put it in geom_*()

Local Data Too!

You can even use different data per layer:

Summary

  • aes() maps variables β†’ visual properties
  • Fixed values go outside aes()
  • Different geom_*() = different visualizations
  • Global (in ggplot()) vs local (in geom_*())