Week 10: Visualizing Data with ggplot2
Unlock the power of the Grammar of Graphics to create insightful plots.
Explore Chapter 10`ggplot()` and `aes()`: Data and Aesthetics.
`ggplot()`
The `ggplot()` function creates the initial plot object. Its most important argument is `data`, which specifies the data frame containing the variables you want to plot.
# Initialize a plot using the mpg dataset
ggplot(data = mpg) # Creates an empty grey background (no layers yet)
`aes()` - Aesthetic Mappings
The `aes()` function defines how variables from your data frame are mapped to visual properties (aesthetics) of the plot layers (geoms). Common aesthetics include:
- `x`: Position on the x-axis.
- `y`: Position on the y-axis.
- `color` (or `colour`): Color of points, lines, outlines.
- `fill`: Fill color of shapes like bars, boxes.
- `size`: Size of points or thickness of lines.
- `shape`: Shape of points.
- `alpha`: Transparency.
You specify mappings within `aes()` like `aes(x = variable1, y = variable2, color = variable3)`.
# Initialize plot, mapping 'displ' (engine displacement) to x-axis
# and 'hwy' (highway miles per gallon) to y-axis
ggplot(data = mpg, mapping = aes(x = displ, y = hwy))
# Still an empty plot, but R now knows which variables map to axes
Mappings defined in the main `ggplot()` call are inherited by subsequent geom layers unless overridden.