# How to Solve R Error: aesthetics must be either length 1 or the same as the data

by | Programming, R, Tips

This error occurs when you try to specify the fill colours when using ggplot2, but the number of colours is not 1 or different from the total number of plots to fill.

To solve this error you can either specify one fill colour argument or ensure the total number of colours matches the number of plots.

This tutorial will go through the error in detail and how to solve it with code examples.

## Example

Consider the following example where we want to plot the miles-per-gallon against the number of cylinders from the built-in R dataset mtcars. We will use a box plot to visualize the distribution of miles-per-gallon values as a function of the number of cylinders.

```library(ggplot2)

ggplot(data = mtcars, aes(x=as.character(cyl), y=mpg)) +
geom_boxplot(fill=c('steelblue', 'red'))```

Let’s run the code to see what happens:

```Error in `check_aesthetics()`:
! Aesthetics must be either length 1 or the same as the data (3): fill```

We get the error because we specified two fill colors but there are more than two box plots to fill. We can verify this by looking at the number of distinct values under the cyl column in mtcars:

```cylinders <- unique(mtcars\$cyl)
num_categories <- length(cylinders)
print(num_categories)```
`3`

There are three distinct values in the cyl column.

### Solution #1

We can solve the error by either specifying one fill colour or by matching the exact number of fill colours to the number of plots. First, let’s look at solving the error with one fill colour:

```library(ggplot2)

ggplot(data = mtcars, aes(x=as.character(cyl), y=mpg)) +
geom_boxplot(fill=c('steelblue'))```

Let’s run the code to get the plot:

In this case, the box plots share the same fill colour.

### Solution #2

Next, we will solve the error by specifying three fill colours.

```library(ggplot2)

ggplot(data = mtcars, aes(x=as.character(cyl), y=mpg)) +
geom_boxplot(fill=c('steelblue', 'green', 'magenta'))```

Let’s run the code to get the plot: