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

岁酱吖の 提交于 2019-12-05 03:44:20

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).

Des %>%
   mutate(nf = cumsum(ACT=="F")) %>%  # build F-to-F groups
   group_by(nf) %>%
   mutate(first24h = as.numeric((DateTime-min(DateTime)) < (24*3600))) %>% # find the first 24h of each F-group
   ggplot(., aes(x=Loq, y=Las)) + 
   geom_path(aes(colour=first24h)) + scale_size(range = c(1, 2))+ geom_point()

At the point: ggplot(., aes(x=Loq, y=Las)) - use '.' to refer to the data as you cant double up

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!