In the context of ggplot, aesthetics are the instructions that determine the visual properties of the plot and its geometries.
Aesthetics can include things like the scales for the x and y axes, the color of the data on the plot based on a property or simply on a color preference, or the size or shape of different geometries.
There are two ways to set aesthetics, by manually specifying individual attributes or by providing aesthetic mappings. We’ll explore aesthetic mappings first and come back to manual aesthetics later in the lesson. Aesthetic mappings “map” variables from the data frame to visual properties in the plot. You can provide aesthetic mappings in two ways using the
aes() mapping function:
- At the canvas level: All subsequent layers on the canvas will inherit the aesthetic mappings you define when you create a ggplot object with
- At the geom level: Only that layer will use the aesthetic mappings you provide.
Let’s discuss inherited aesthetics first, or aesthetics you define at the canvas level. Here’s an example of code that assigns
aes() mappings for the
y scales at the canvas level:
viz <- ggplot(data=airquality, aes(x=Ozone, y=Temp)) + geom_point() + geom_smooth()
In the example above:
- The aesthetic mapping is wrapped in the
aes()aesthetic mapping function as an additional argument to
- Both of the subsequent geom layers,
geom_smooth()use the scales defined inside the aesthetic mapping assigned at the canvas level.
You should set aesthetics for subsequent layers at the canvas level if all layers will share those aesthetics.
In the visualization we will be creating, we want to plot the Movie Ratings (
imdbRating) on the
x axis and the number of awards (
nrOfWins) on the
y axis to see if there is a correlation between a movie rating and the number of awards it wins. We will use this scale on the subsequent layers, so create the aesthetic mappings at the canvas level.