How do I access the data frame that has been passed to ggplot()?

强颜欢笑 提交于 2019-11-29 09:26:05
mtcars %>% {
  ggplot(., aes(mpg, hp)) + 
  labs(title = paste("N =", nrow(.))) + 
  geom_point()
}

Note that when wrapping the whole ggplot call in {...} curly braces, you must use the . dot pronoun for the data argument in ggplot(., ...). Then you can call back that object using the . pronoun anywhere in the call.

Another option that takes advantage of another of magrittr's pipe-lining features: the tee operator %T>%.

library(ggplot2)
library(magrittr)
# to solidify where the variable will be out-of-scope defined
nr <- "oops"
mtcars %T>%
  { nr <<- nrow(.) } %>%
  ggplot(aes(mpg, hp)) + 
    labs(title=sprintf("N=%i", nr)) + 
  geom_point()

(This can also be done using dplyr's do({nr <<- nrow(.)}) %>%.)

This differs from Brian's answer in two ways:

  1. Subjectively "cleaner looking", in that the ggplot code is not indented within a code block. (As commented, though, the blending of different pipelines could be a negative as well.)

  2. It has side-effect, by creating nr outside of the pipeline and ggplot pipes. By pre-assigning nr, I think this mitigates reaching outside of the local environment, but it's still a little sloppy.

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