How to Fix in R: error: `mapping` must be created by `aes()`


One error you may encounter when using R is:

Error: `mapping` must be created by `aes()`

This error occurs when you attempt to use the aes() argument when creating a plot in ggplot2 and use it in the incorrect place or use it without the ‘mapping’ syntax.

The following example shows how to fix this error in practice.

How to Reproduce the Error

Suppose we attempt to create a boxplot using ggplot2:

library(ggplot2)

#create data
df <- data.frame(y=c(2, 3, 3, 4, 5, 5, 6, 7, 8, 8, 9, 10, 16, 19, 28),
                 x1=c(1, 2, 2, 3, 5, 6, 8, 8, 9, 9, 10, 11, 12, 15, 15),
                 x2=c(8, 7, 7, 6, 6, 4, 3, 5, 4, 6, 5, 4, 3, 2, 2))

#attempt to create boxplot for 'x1' variable
ggplot() +
  geom_boxplot(df, aes(x=x1))

Error: `mapping` must be created by `aes()`

We receive an error because the aes() argument is used in the geom_boxplot() function without using the ‘mapping’ syntax.

How to Fix the Error

There are two ways to fix this error.

Method 1: Use ‘mapping’ Syntax

One way to fix the error is to specifically use the ‘mapping’ syntax in front of the aes() argument:

library(ggplot2)

#create data
df <- data.frame(y=c(2, 3, 3, 4, 5, 5, 6, 7, 8, 8, 9, 10, 16, 19, 28),
                 x1=c(1, 2, 2, 3, 5, 6, 8, 8, 9, 9, 10, 11, 12, 15, 15),
                 x2=c(8, 7, 7, 6, 6, 4, 3, 5, 4, 6, 5, 4, 3, 2, 2))

#create boxplot for 'x1' variable
ggplot() +
  geom_boxplot(df, mapping=aes(x=x1))

Since we explicitly used the mapping syntax, we avoided any error.

Method 2: Use ‘aes’ in ggplot Function

Another way to fix this error is to use the aes() argument within the ggplot() function:

library(ggplot2)

#create data
df <- data.frame(y=c(2, 3, 3, 4, 5, 5, 6, 7, 8, 8, 9, 10, 16, 19, 28),
                 x1=c(1, 2, 2, 3, 5, 6, 8, 8, 9, 9, 10, 11, 12, 15, 15),
                 x2=c(8, 7, 7, 6, 6, 4, 3, 5, 4, 6, 5, 4, 3, 2, 2))

#create boxplot for 'x1' variable
ggplot(df, aes(x=x1)) +
  geom_boxplot()

We’re able to successfully create the boxplot and avoid any errors because we used the aes() argument within the ggplot() function.

Additional Resources

The following tutorials explain how to fix other common errors in R:

How to Fix in R: plot.new has not been called yet
How to Fix in R: invalid model formula in ExtractVars
How to Fix in R: replacement has length zero

Leave a Reply

Your email address will not be published.