循环遍历ggplot列表中的x轴和y轴变量并打印图表

时间:2017-12-06 22:48:55

标签: r plot ggplot2

我经历了这个question,但它只绕x轴循环,我怎样才能在x轴和y轴上循环。我尝试如下,但它不打印网格中的每个图: 谢谢!

例如,我有一个数据框:

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))
在右侧获得常见图例的功能:
 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))
    }
实际绘图循环:
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]]))
  }

1 个答案:

答案 0 :(得分:1)

这个怎么样?

Store your assets in the assets/ directory at the root of your project.

enter image description here