ggplot2 aes Function in R

05.16.2021

Intro

The aes function is a method in ggplot2 called an Aesthetic Mapping. This function allows you to map data, features or columns from your data set to the map. The basic example is as follows.

aes(x, y)

This aesthetic will create a map from x to y for your plot.

You almost always pass the function to a ggplot call to create a base plot before adding a geometry. Here is a full example in context.

ggplot(mpg, aes(x = displ, y = hwy)) 
    + geom_point()

Some Extra Details

There is more you can do with aes and more you might see when reviewing tutorials or docs online. Let’s walk through some examples of aes you might see.

You may see that we can create an aes without specifying the x and y names for the pareters. In the following aes, the x and y are infered.

aes(mpg, wt)

You can also modify x and y with calculations.

aes(x = mpg ^ 2, y = wt / cyl)

You may also see the use of shape and colour (or color for US). Using these parameters usually creates groups of plots by a factor. Here are two examples.

library(ggplot2)
ggplot(mpg, aes(x = displ, y = hwy, colour = trans)) + geom_point()

unnamed chunk 1 1

ggplot(mpg, aes(x = displ, y = hwy, shape = trans)) + geom_point()
## Warning: The shape palette can deal with a maximum of 6 discrete values because
## more than 6 becomes difficult to discriminate; you have 10. Consider
## specifying shapes manually if you must have them.

## Warning: Removed 96 rows containing missing values (geom_point).

unnamed chunk 2 1