Error in ggplot.data.frame : Mapping should be created with aes or aes_string

The error (in the title of the post) arises because you have too many arguments to ggplot. As the comments to the question note, the pipeline %>% implicitly includes the output from the left-hand side of the pipe as the first argument to the function on the righthand side.

# these have the same meaning
f(x, y)
x %>% f(y)

This code replicates the same kind of error. (I’ve separated out the aes mapping to its own step for clarity.)

mtcars %>% 
  filter(am == 1) %>% 
  ggplot(mtcars) + 
  aes(x = mpg, y = wt) + 
  geom_point()
#> Error in ggplot.data.frame(., mtcars) : 
#>   Mapping should be created with aes or aes_string

Conceptually–if you “unpipe” things–what’s being executed is the something like following:

ggplot(filter(mtcars, am == 1), mtcars)

The ggplot function assumes the first argument is the data parameter and the second is an aes aesthetic mapping. But in your pipeline, the first two arguments are data frames. This is the source of the error.

The solution is to remove the redundant data argument. More generally, I separate my data transformation pipeline (%>% chains) from my ggplot plot building (+ chains).

Leave a Comment