如何访问已传递给ggplot()的数据帧? [英] How do I access the data frame that has been passed to ggplot()?
问题描述
我想将字符串N=xxx
设置为图形的标题,其中xxx
是作为ggplot()
的data
参数传递的数据帧中的观察值.在我当前的代码中,我第二次显式传递该数据帧作为sprintf()
的参数,该参数在labs()
中使用:
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()
这确实会产生所需的标题,但是它不适用于更复杂的任务:我使用dplyr
管道来构造要绘制的数据框,由于这是一个耗时的过程,因此我不会不想像示例中那样再次重复管道以获取行数.
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.
那么,如何从用于修改绘图的函数的参数规范中访问作为参数传递给ggplot()
的数据框?
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?
推荐答案
mtcars %>% {
ggplot(., aes(mpg, hp)) +
labs(title = paste("N =", nrow(.))) +
geom_point()
}
请注意,在将整个ggplot
调用包装在{...}
大括号中时,必须将.
点代词用于ggplot(., ...)
中的data参数.然后,您可以在通话中的任何位置使用.
代词回叫该对象.
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.
这篇关于如何访问已传递给ggplot()的数据帧?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!