Home » How to Fix: aesthetics must be either length 1 or the same as the data

How to Fix: aesthetics must be either length 1 or the same as the data

by Tutor Aspire

One error you may encounter in R is:

Error: Aesthetics must be either length 1 or the same as the data (5): fill

This error occurs when you attempt to specify the fill colors to use in a ggplot2 plot, yet the number of colors you specified is different than 1 or different than the total number of objects to be filled.

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

How to Reproduce the Error

Suppose we’re working with the built-in R dataset called airquality:

#view first six lines of airquality dataset
head(airquality)

  Ozone Solar.R Wind Temp Month Day
1    41     190  7.4   67     5   1
2    36     118  8.0   72     5   2
3    12     149 12.6   74     5   3
4    18     313 11.5   62     5   4
5    NA      NA 14.3   56     5   5
6    28      NA 14.9   66     5   6

Now suppose we attempt to create multiple boxplots to visualize the distribution of Ozone values for each Month:

library(ggplot2)

#attempt to create multiple boxplots
ggplot(data = airquality, aes(x=as.character(Month), y=Temp)) +
    geom_boxplot(fill=c('steelblue', 'red'))

Error: Aesthetics must be either length 1 or the same as the data (5): fill

We receive an error because there are 5 unique Months in the dataset (thus, we will create 5 boxplots) but we only supplied two colors to the fill argument.

How to Fix the Error

There are two ways to fix this error:

Method 1: Only Use One Color in Fill Argument

We could choose to use just one color in the fill argument:

library(ggplot2)
ggplot(data = airquality, aes(x=as.character(Month), y=Temp)) +
    geom_boxplot(fill=c('steelblue'))

This allows us to fill in each boxplot with the same color.

Method 2: Use the Same Number of Colors as the Number of Boxplots

We could also specify five colors to use since this matches the number of boxplots we will create:

library(ggplot2)
ggplot(data = airquality, aes(x=as.character(Month), y=Temp)) +
    geom_boxplot(fill=c('steelblue', 'red', 'purple', 'green', 'orange'))

We don’t receive and error because the number of colors we supplied matches the number of boxplots.

Additional Resources

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

How to Fix: Discrete value supplied to continuous scale
How to Fix: argument is not numeric or logical: returning na
How to Fix: replacement has length zero

You may also like