我想使用ggplot循环遍历多个列以创建多个绘图,但在for循环中使用占位符会更改ggplot的行为.
如果我有这个:
t <- data.frame(w = c(1, 2, 3, 4), x = c(23,45,23, 34),
y = c(23,34,54, 23), z = c(23,12,54, 32))
Run Code Online (Sandbox Code Playgroud)
这很好用:
ggplot(data=t, aes(w, x)) + geom_line()
Run Code Online (Sandbox Code Playgroud)
但这不是:
i <- 'x'
ggplot(data=t, aes(w, i)) + geom_line()
Run Code Online (Sandbox Code Playgroud)
如果我想最终遍历x,y和z,那么这是一个问题.有帮助吗?
Mat*_*ker 39
你只需要使用aes_string而不是aes像这样:
ggplot(data=t, aes_string(x = "w", y = i)) + geom_line()
Run Code Online (Sandbox Code Playgroud)
请注意,w那么也需要指定为字符串.
Tun*_*ung 11
ggplot2 v3.0.02018年7月发布的版本支持诸如!!(bang bang)内部的整洁评估aes()。因此,我们可以执行以下操作:
构建一个将x-和y-列名称作为输入的函数。注意rlang::sym&的使用!!。
然后使用循环遍历每一列purrr::map。
library(rlang)
library(tidyverse)
dt <- data.frame(
w = c(1, 2, 3, 4), x = c(23, 45, 23, 34),
y = c(23, 34, 54, 23), z = c(23, 12, 54, 32)
)
Run Code Online (Sandbox Code Playgroud)
定义一个接受字符串作为输入的函数
plot_for_loop <- function(df, .x_var, .y_var) {
# convert strings to variable
x_var <- sym(.x_var)
y_var <- sym(.y_var)
# unquote variables using !!
ggplot(df, aes(x = !! x_var, y = !! y_var)) +
geom_point() +
geom_line() +
labs(x = x_var, y = y_var) +
theme_classic(base_size = 12)
}
Run Code Online (Sandbox Code Playgroud)
遍历每一列
plot_list <- colnames(dt)[-1] %>%
map( ~ plot_for_loop(dt, colnames(dt)[1], .x))
# view all plots individually (not shown)
plot_list
# Combine all plots
library(cowplot)
plot_grid(plotlist = plot_list,
ncol = 3)
Run Code Online (Sandbox Code Playgroud)

编辑:上述功能也可以写成W / O型sym和!!
plot_for_loop2 <- function(df, x_var, y_var) {
ggplot(df, aes(x = .data[[x_var]], y = .data[[y_var]])) +
geom_point() +
geom_line() +
labs(x = x_var, y = y_var) +
theme_classic(base_size = 12)
}
Run Code Online (Sandbox Code Playgroud)
或者我们可以在将数据帧从宽格式转换为长格式()之后使用facet_grid/facet_wraptidyr::gather
dt_long <- dt %>%
tidyr::gather(key, value, -w)
dt_long
#> w key value
#> 1 1 x 23
#> 2 2 x 45
#> 3 3 x 23
#> 4 4 x 34
#> 5 1 y 23
#> 6 2 y 34
#> 7 3 y 54
#> 8 4 y 23
#> 9 1 z 23
#> 10 2 z 12
#> 11 3 z 54
#> 12 4 z 32
### facet_grid
ggp1 <- ggplot(dt_long,
aes(x = w, y = value, color = key, group = key)) +
facet_grid(. ~ key, scales = "free", space = "free") +
geom_point() +
geom_line() +
theme_bw(base_size = 14)
ggp1
Run Code Online (Sandbox Code Playgroud)

### facet_wrap
ggp2 <- ggplot(dt_long,
aes(x = w, y = value, color = key, group = key)) +
facet_wrap(. ~ key, nrow = 2, ncol = 2) +
geom_point() +
geom_line() +
theme_bw(base_size = 14)
ggp2
Run Code Online (Sandbox Code Playgroud)

### bonus: reposition legend
# https://cran.r-project.org/web/packages/lemon/vignettes/legends.html
library(lemon)
reposition_legend(ggp2 + theme(legend.direction = 'horizontal'),
'center', panel = 'panel-2-2')
Run Code Online (Sandbox Code Playgroud)
