简体   繁体   中英

Loop over both the x-axis and y-axis variables in ggplot list and print plots

I went through this question but it only loops through the x-axis, how can I loop through both x and y axis. I tried it as follows but it does not print each plot in grid: Thanks!

For example I have a dataframe:

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))
Function to get common legend on the right:
  grid_arrange_shared_legend <- function(...) { plots <- list(...) g <- ggplotGrob(plots[[1]] + theme(legend.position="right"))$grobs legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]] lw <- sum(legend$width) gl <- lapply(plots, function(x) x + theme(legend.position="none")) grid.arrange(arrangeGrob(grobs = gl), legend, ncol = 2, widths = unit.c(unit(1, "npc") - lw, lw)) } 
Actual plotting loop:
 qual = c("w", "x") for(q in qual){ p = lapply(list("y", "z"), function(l) ggplot(t, aes_string(x=l, y=q)) + geom_point(aes(col=plate_name), size=2.0) + xlab(l) + ylab(q) + geom_smooth(method="lm") + scale_color_brewer(palette = "Paired") + theme_bw()) #pdf("x_vs_y_gg.pdf", h=3.5*3, w=14) print(grid_arrange_shared_legend(p[[1]], p[[2]], p[[3]], p[[4]], p[[5]], p[[6]], p[[7]], p[[8]])) } 

What about this ?

library(ggplot2)
library(gridExtra)

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),
                plate_name=LETTERS[1:4])

 grid_arrange_shared_legend <- function(plots) {
      g <- ggplotGrob(plots[[1]] + theme(legend.position="right"))$grobs
      legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]]
      lw <- sum(legend$width)
      gl <- lapply(plots, function(x) x + theme(legend.position="none"))
      grid.arrange(arrangeGrob(grobs = gl), legend,
                   ncol = 2, widths = unit.c(unit(1, "npc") - lw, lw))
    }

myfun <- function(l,q) ggplot(t, aes(x=get(l), y=get(q))) + 
               geom_point(aes(col=plate_name), size=2.0) + 
               xlab(l) + ylab(q) +
               geom_smooth(method="lm") +
               scale_color_brewer(palette = "Paired") +
               theme_bw()

cmb <- combn(names(t)[-ncol(t)],2)
lst <- mapply(myfun, cmb[1,], cmb[2,], SIMPLIFY = F)

grid_arrange_shared_legend(lst)

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM