Aesthetic mappings describe how properties of the data connect with
features of the graph, such as distance along an axis, size, or color.
The aes
function connects data with what we see on the graph by
defining aesthetic mappings and will be one of the functions you use
most often when plotting. The outcome of the aes
function is often
used as the argument of a geometry function. This example produces a
scatterplot of total murders versus population in millions:
murders %>% ggplot() +
geom_point(aes(x = population/10^6, y = total))
We can drop the x =
and y =
if we wanted to since these are the
first and second expected arguments, as seen in the help page.
Instead of defining our plot from scratch, we can also add a layer to
the p
object that was defined above as p <- ggplot(data = murders)
:
p + geom_point(aes(population/10^6, total))
The scale and labels are defined by default when adding this layer. Like
dplyr functions, aes
also uses the variable names from the object
component: we can use population
and total
without having to call
them as murders$population
and murders$total
. The behavior of
recognizing the variables from the data component is quite specific to
aes
. With most functions, if you try to access the values of
population
or total
outside of aes
you receive an error.