0. test_data

  1. mydata <- data.frame("Y1"=rnorm(20),
  2. "Y2"=runif(20, min=10, max=20),
  3. "X1"=rep(LETTERS[1:4],each=5),
  4. "X2"=rep(c("t1","t2","t3","t4","t5"),4))

1. loop (assign + get)

  1. library(ggplot2)
  2. library(ggpubr)
  3. # 构造数据
  4. mydata <- data.frame("Y1"=rnorm(20),
  5. "Y2"=runif(20, min=10, max=20),
  6. "X1"=rep(LETTERS[1:4],each=5),
  7. "X2"=rep(c("t1","t2","t3","t4","t5"),4))
  8. # 对每对因变量和自变量画图
  9. # 设置k以命名用于存储图片的一系列对象列表p1,p2,p3,p4
  10. k <- 0
  11. for (i in c("Y1","Y2")) {
  12. for (j in c("X1","X2")) {
  13. p <- ggplot(mydata)+geom_boxplot(aes_string(x=j,y=i))+
  14. labs(title = paste(i,"-", j, sep = ""))
  15. k <- k+1
  16. assign(paste("p", k, sep = ""), p)
  17. }
  18. }
  19. # 拼图
  20. plotlist <- lapply(ls(pattern = "^p[0-9]"), get)
  21. ggarrange(plotlist = plotlist, ncol = 2, nrow = 2)

2. loop (list)

  1. library(ggplot2)
  2. p <- list()
  3. for (i in c("Y1", "Y2")) {
  4. for (j in c("X1", "X2")) {
  5. p <- c(p,
  6. list(ggplot(mydata) +
  7. geom_boxplot(aes_string(x = j, y = i)) +
  8. labs(title = paste(i, "-", j, sep = ""))))
  9. }
  10. }
  11. Rmisc::multiplot(plotlist = p, layout = matrix(1:4, nrow = 2))

3. mapply

  1. myplot <- function(j, i) {
  2. ggplot(mydata) +
  3. geom_boxplot(aes_string(x = j, y = i)) +
  4. labs(title = paste(i,"-", j, sep = ""), x = j, y = i)
  5. }
  6. # 批量生成 list
  7. p <- mapply(myplot, i = c("Y1","Y2","Y2","Y1"), j = c("X1","X2"), SIMPLIFY = FALSE)
  8. Rmisc::multiplot(plotlist = p, layout = matrix(1:4, nrow = 2))

4. tidyr (re)

  1. library(ggplot2)
  2. library(tidyr)
  3. data.frame("Y1"=rnorm(20),
  4. "Y2"=runif(20, min=10, max=20),
  5. "X1"=rep(LETTERS[1:4],each=5),
  6. "X2"=rep(c("t1","t2","t3","t4","t5"),4)) %>%
  7. gather("Ys", "Y", 1:2) %>%
  8. gather("Xs", "X", 1:2) %>%
  9. ggplot(aes(X, Y)) + geom_boxplot() + facet_grid(Ys ~ Xs, scales = "free")