0. test_data
mydata <- data.frame("Y1"=rnorm(20),
"Y2"=runif(20, min=10, max=20),
"X1"=rep(LETTERS[1:4],each=5),
"X2"=rep(c("t1","t2","t3","t4","t5"),4))
1. loop (assign + get)
library(ggplot2)
library(ggpubr)
# 构造数据
mydata <- data.frame("Y1"=rnorm(20),
"Y2"=runif(20, min=10, max=20),
"X1"=rep(LETTERS[1:4],each=5),
"X2"=rep(c("t1","t2","t3","t4","t5"),4))
# 对每对因变量和自变量画图
# 设置k以命名用于存储图片的一系列对象列表p1,p2,p3,p4
k <- 0
for (i in c("Y1","Y2")) {
for (j in c("X1","X2")) {
p <- ggplot(mydata)+geom_boxplot(aes_string(x=j,y=i))+
labs(title = paste(i,"-", j, sep = ""))
k <- k+1
assign(paste("p", k, sep = ""), p)
}
}
# 拼图
plotlist <- lapply(ls(pattern = "^p[0-9]"), get)
ggarrange(plotlist = plotlist, ncol = 2, nrow = 2)
2. loop (list)
library(ggplot2)
p <- list()
for (i in c("Y1", "Y2")) {
for (j in c("X1", "X2")) {
p <- c(p,
list(ggplot(mydata) +
geom_boxplot(aes_string(x = j, y = i)) +
labs(title = paste(i, "-", j, sep = ""))))
}
}
Rmisc::multiplot(plotlist = p, layout = matrix(1:4, nrow = 2))
3. mapply
myplot <- function(j, i) {
ggplot(mydata) +
geom_boxplot(aes_string(x = j, y = i)) +
labs(title = paste(i,"-", j, sep = ""), x = j, y = i)
}
# 批量生成 list
p <- mapply(myplot, i = c("Y1","Y2","Y2","Y1"), j = c("X1","X2"), SIMPLIFY = FALSE)
Rmisc::multiplot(plotlist = p, layout = matrix(1:4, nrow = 2))
4. tidyr (re)
library(ggplot2)
library(tidyr)
data.frame("Y1"=rnorm(20),
"Y2"=runif(20, min=10, max=20),
"X1"=rep(LETTERS[1:4],each=5),
"X2"=rep(c("t1","t2","t3","t4","t5"),4)) %>%
gather("Ys", "Y", 1:2) %>%
gather("Xs", "X", 1:2) %>%
ggplot(aes(X, Y)) + geom_boxplot() + facet_grid(Ys ~ Xs, scales = "free")