Error: Aesthetics must be either length 1 or the same as the data (22): x Run `rlang::last_error()` to see where the error occurred.

Trying to make boxplots but both p2 and p3 are giving me the same error, and I cannot figure out how to correct it. Or what the error means to begin with.

p1 <- ggplot(data = iMaine, aes(x = State, y = `Arrests related to Marijuana`)) + geom_boxplot()
p2 <- ggplot(data = iMaine, aes(Maine)) + geom_density()
p3 <- ggplot(data = iMaine, aes(NewHampshire)) + geom_density()
multiplot(p1, p2, p3, cols = 3)

We don't know what your data looks like, but I'd guess that Maine and NewHampshire are vectors. When you run ggplot(data = iMaine, aes(Maine)) + geom_density(), ggplot is expecting Maine to be a column of the data frame iMaine.

If there's no column called Maine in the data frame iMaine, ggplot will still "work" (produce a plot) if Maine is a separate vector (that is, not part of iMaine), and has length equal to 1 or length equal to the number of rows in iMaine (22 in this case). (Though you shouldn't do this, because it breaks the link between the data frame you've fed to ggplot and the columns of data referenced inside aes.)

The two examples below illustrate what I'm talking about. I've used the built-in data frame mtcars (which has 32 rows) for illustration. In the first case, I've created a separate data vector called Maine and it has 10 values. ggplot throws the same error you got, because Maine has 10 values instead of 1 or 32. The second example "works" because Maine now has 32 values, which is the same as the number of rows in mtcars. This is just for illustration. Maine has nothing to do with mtcars and using ggplot this way might give results that are wrong or not what you intended.


ggplot(mtcars, aes(Maine)) + geom_density()
#> Error: Aesthetics must be either length 1 or the same as the data (32): x

ggplot(mtcars, aes(Maine)) + geom_density()

Created on 2021-04-02 by the reprex package (v1.0.0)

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.