在ggplot中使用参数占位符

编程入门 行业动态 更新时间:2024-10-24 18:17:48
本文介绍了在ggplot中使用参数占位符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我试图在ggplot()中使用参数占位符..但这由于某种原因我无法完全确定.

I am trying to use an argument place holder . within a ggplot(). But it doesn't work for some reason I am not entirely sure of.

我正在做的是这件事(使用来自ggplot2/tidyverse的示例数据):

What I am doing is this (using the sample data from ggplot2/the tidyverse):

library(tidyverse) library(magrittr) corr_eqn <- function(x, y, digits = 2) { corr_coef <- round(cor(x, y, use = "pairwiseplete.obs"), digits = digits) paste("r = ", corr_coef) } economics %>% filter(date >= "1990-11-01") %>% ggplot(aes(pop, unemploy)) + geom_point()+ annotate(geom = "text", x=-Inf, y=Inf, hjust=0, vjust=1, label = economics[economics$date>="1990-11-01",] %$% corr_eqn(pop, unemploy))

但是,我想将标签后面的命令减少为label = . %$% corr_eqn(pop, unemploy). IE.我不想再次致电economics[economics$date>="1990-11-01",],因为我已经对此进行了过滤:

However, I want to reduce the command behind label to label = . %$% corr_eqn(pop, unemploy). I.e. I do not want to call economics[economics$date>="1990-11-01",] again as I have already filtered for this:

economics %>% filter(date >= "1990-11-01") %>% ggplot(aes(pop, unemploy)) + geom_point()+ annotate(geom = "text", x=-Inf, y=Inf, hjust=0, vjust=1, label = . %$% corr_eqn(pop, unemploy))

但是,它不适用于自变量占位符..我该怎么办?

However, it doesn't work with the argument place holder .. What should I do instead?

此外,如果可以不必再次将pop和unemploy列为corr_eqn fn中的单独参数,这也将是惊人的.

Plus, if it would be possible to nat having to list pop and unemploy as seperate arguments in the corr_eqn fn again, this would be also amazing.

推荐答案

问题是annotate不在管道中,因此.在这里没有意义. ggplot中的+运算符与magrittr中的%>%具有不同的功能;在您的代码中,管道实际上在对ggplot()的调用处停止. +运算符将允许下一个函数向绘图中添加各种元素,但通常不允许您以与%>%相同的方式访问馈入ggplot()调用的数据操作员.

The problem is that annotate is not within the pipe, so . has no meaning there. The + operator in ggplot does not have the same function as the %>% in magrittr; in your code the pipe effectively stops at the call to ggplot(). The + operator will allow the next function to add various elements to the plot, but it won't in general allow you to access the data that was fed to the ggplot() call in the way you would with the %>% operator.

另一方面,如果使用geom_text而不是annotate,这些问题将消失,因为直接访问子集数据中的变量:

On the other hand, if you use geom_text instead of annotate, these problems vanish because you are accessing the variables in your subsetted data directly:

economics %>% filter(date >= "1990-11-01") %>% ggplot(aes(pop, unemploy)) + geom_point() + geom_text(aes(x = min(pop), y = max(unemploy), label = corr_eqn(pop, unemploy)), hjust = 0, vjust = 1, size = 6)

更多推荐

在ggplot中使用参数占位符

本文发布于:2023-10-23 06:05:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1520012.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:参数   ggplot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!