我正在编写一个自定义函数,以创建一个散点图,并在点上附加标签。这是相同内容的最低要求。
# needed libraries
library(tidyverse)
library(ggplot2)
library(ggrepel)
# custom function
label_adder <- function(data, x, y, label.var) {
# basic plot
plot <-
ggplot(data = data,
mapping = aes(
x = !!rlang::enquo(x),
y = !!rlang::enquo(y)
)) +
geom_point() +
geom_smooth(method = "lm")
# adding label
plot <-
plot +
geom_label_repel(mapping = aes(label = !!rlang::enquo(label.var)))
return(plot)
}
# creating dataframe
mtcars_new <- mtcars %>%
tibble::rownames_to_column(., var = "car") %>%
tibble::as_data_frame(x = .)
# using the function
label_adder(
data = mtcars_new,
x = wt,
y = mpg,
label.var = car
)
由reprex package(v0.2.0.9000)于2018-08-30创建。
问题
我似乎无法弄清楚如何使标签取决于x
和y
变量的值。例如,假设用户不想显示散点图中的所有点,而只显示带有(示例)的点:
wt > 5
wt < 4 & mpg < 20
wt > 4 | mpg > 25
等
我可以使用geom_label_repel
在rlang
的代码中进行哪些更改,以便评估用户提供的任何条件(涉及x
和/或y
),并且仅这些标签会显示在绘图中吗?
答案 0 :(得分:3)
您可以尝试类似的方法。在这里,我向您的函数添加了一个表达式参数,检查是否正在使用表达式,然后进行相应的过滤。
library(tidyverse)
library(ggplot2)
library(ggrepel)
# custom function
label_adder <- function(data, x, y, label.var, exp = NULL) {
param_list <- as.list(match.call())
if("exp" %in% names(param_list)){
plot <-
ggplot(
mapping = aes(
x = !!rlang::enquo(x),
y = !!rlang::enquo(y)
)) +
geom_point(data = data) +
geom_smooth(data = data, method = "lm")+
geom_label_repel(data = data %>% filter(!!rlang::enquo(exp)),
mapping = aes(label = !!rlang::enquo(label.var)))
return(plot)
}
else{
plot <-
ggplot(data = data,
mapping = aes(
x = !!rlang::enquo(x),
y = !!rlang::enquo(y)
)) +
geom_point() +
geom_smooth(method = "lm")+
geom_label_repel(mapping = aes(label = !!rlang::enquo(label.var)))
return(plot)
}
}
# creating dataframe
mtcars_new <- mtcars %>%
tibble::rownames_to_column(., var = "car") %>%
tibble::as_data_frame(x = .)
# using the function
label_adder(
data = mtcars_new,
x = wt,
y = mpg,
label.var = car
)
label_adder(
data = mtcars_new,
x = wt,
y = mpg,
label.var = car,
exp = wt < 4 & mpg < 20
)
由reprex package(v0.2.0)于2018-08-30创建。
更新
label_adder <- function(data, x, y, label.var, exp = NULL) {
param_list <- as.list(match.call())
if("exp" %in% names(param_list)){
my_exp <- rlang::enquo(exp)
}
else{
a <- "row_number() > 0"
my_exp <- rlang::quo(!! rlang::sym(a))
}
plot <-
ggplot(
mapping = aes(
x = !!rlang::enquo(x),
y = !!rlang::enquo(y)
)) +
geom_point(data = data) +
geom_smooth(data = data, method = "lm")+
geom_label_repel(data = data %>% filter(!!my_exp),
mapping = aes(label = !!rlang::enquo(label.var)))
return(plot)
}
这仍然使用if
和else
,但是不需要上面所有的额外代码。