所以我们在这里编辑函数,使过滤更加灵活。
# loading needed libraries
library(tidyverse)
library(ggplot2)
library(ggrepel)
# custom function
label_adder <- function(data, x, y, label.var, exp = NULL) {
param_list <- as.list(match.call())
label_data <- data %>% {if ("exp" %in% names(param_list)) filter(., !!enquo(exp)) else .}
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 = label_data,
mapping = aes(label = !!rlang::enquo(label.var))
)
return(plot)
}
df.listcol <- datasets::iris %>%
dplyr::mutate(.data = ., Species2 = Species) %>% # just creates a copy of this variable
dplyr::group_by(.data = ., Species) %>%
tidyr::nest(data = .)
test <- df.listcol %>% mutate(plot = map(data, ~label_adder(., x = Sepal.Length, label.var = Species2, y = Sepal.Width)))
test
#> # A tibble: 3 x 3
#> Species data plot
#> <fct> <list> <list>
#> 1 setosa <tibble [50 Ã 5]> <S3: gg>
#> 2 versicolor <tibble [50 Ã 5]> <S3: gg>
#> 3 virginica <tibble [50 Ã 5]> <S3: gg>
test$plot[[2]]
test2 <- df.listcol %>% mutate(plot = map(data, ~label_adder(., x = Sepal.Length, label.var = Species2, y = Sepal.Width, exp = Sepal.Length > 6.5)))
test2
#> # A tibble: 3 x 3
#> Species data plot
#> <fct> <list> <list>
#> 1 setosa <tibble [50 Ã 5]> <S3: gg>
#> 2 versicolor <tibble [50 Ã 5]> <S3: gg>
#> 3 virginica <tibble [50 Ã 5]> <S3: gg>
test2$plot[[2]]
reprex
package
(第0.2.0版)。