geom_text 的包装函数
Wrapper function for geom_text
这个问题与密切相关。但是,我想围绕 geom_text
函数构建一个包装器。
查看此示例(使用 tidyverse
中的示例数据):
library(tidyverse)
corr_eqn <- function(x, y, digits = 2) {
corr_coef <-
round(cor(x, y, use = "pairwise.complete.obs"), digits = digits)
paste("r = ", corr_coef)
}
geom_text_pearson <- function(x_ax, y_ax, ...){
geom_text(aes(x = min(x_ax), y = max(y_ax), label = corr_eqn(x_ax, y_ax)),
hjust = 0, vjust = 1, size = 6)
}
economics %>%
filter(date >= "1990-11-01") %>%
ggplot(aes(pop, unemploy)) +
geom_point() +
geom_text_pearson(x_ax = pop, y_ax= unemploy)
如果我用
替换我的服装 geom_text_pearson
功能,我会得到我想要的结果
geom_text(aes(x = min(pop), y = max(unemploy), label = corr_eqn(pop, unemploy)),
hjust = 0, vjust = 1, size = 6)
有没有办法通过我的首选解决方案来做到这一点?
由于您将参数传递给使用非标准评估的函数,因此您需要将参数包装在 {{
(卷曲运算符)中。
请注意,正如@user20650 在对我之前回答的评论中所建议的那样,您的 geom_text_pearson
函数将受益于添加 check_overlap = TRUE
:
geom_text_pearson <- function(x_ax, y_ax, ...){
geom_text(aes(x = min({{x_ax}}), y = max({{y_ax}}),
label = corr_eqn({{x_ax}}, {{y_ax}})),
hjust = 0, vjust = 1, size = 6, check_overlap = TRUE)
}
economics %>%
filter(date >= "1990-11-01") %>%
ggplot(aes(pop, unemploy)) +
geom_point() +
geom_text_pearson(x_ax = pop, y_ax= unemploy)
这个问题与geom_text
函数构建一个包装器。
查看此示例(使用 tidyverse
中的示例数据):
library(tidyverse)
corr_eqn <- function(x, y, digits = 2) {
corr_coef <-
round(cor(x, y, use = "pairwise.complete.obs"), digits = digits)
paste("r = ", corr_coef)
}
geom_text_pearson <- function(x_ax, y_ax, ...){
geom_text(aes(x = min(x_ax), y = max(y_ax), label = corr_eqn(x_ax, y_ax)),
hjust = 0, vjust = 1, size = 6)
}
economics %>%
filter(date >= "1990-11-01") %>%
ggplot(aes(pop, unemploy)) +
geom_point() +
geom_text_pearson(x_ax = pop, y_ax= unemploy)
如果我用
替换我的服装geom_text_pearson
功能,我会得到我想要的结果
geom_text(aes(x = min(pop), y = max(unemploy), label = corr_eqn(pop, unemploy)),
hjust = 0, vjust = 1, size = 6)
有没有办法通过我的首选解决方案来做到这一点?
由于您将参数传递给使用非标准评估的函数,因此您需要将参数包装在 {{
(卷曲运算符)中。
请注意,正如@user20650 在对我之前回答的评论中所建议的那样,您的 geom_text_pearson
函数将受益于添加 check_overlap = TRUE
:
geom_text_pearson <- function(x_ax, y_ax, ...){
geom_text(aes(x = min({{x_ax}}), y = max({{y_ax}}),
label = corr_eqn({{x_ax}}, {{y_ax}})),
hjust = 0, vjust = 1, size = 6, check_overlap = TRUE)
}
economics %>%
filter(date >= "1990-11-01") %>%
ggplot(aes(pop, unemploy)) +
geom_point() +
geom_text_pearson(x_ax = pop, y_ax= unemploy)