Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

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

I want to set the string N=xxx as the title of my figure, where xxx is the number of observations in the data frame that I pass as the data argument to ggplot(). In my current code, I explicitly pass that data frame a second time as an argument to sprintf() which I use inside of labs():

ggplot(mtcars, aes(mpg, hp)) + 
    labs(title=sprintf("N=%i", nrow(mtcars))) + 
    geom_point()

This does produce the desired title, but it won't work with more complex tasks: I use a dplyr pipe to construct the data frame that is being plotted, and as this is a time-consuming process, I wouldn't want to repeat the pipe a second time to obtain the number of rows like in the example.

So, how do I access the data frame that has been passed as an argument to ggplot() from within the argument specifications of the functions that are used to modify the plot?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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.

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...