【问题标题】:Loop over both the x-axis and y-axis variables in ggplot list and print plots循环遍历 ggplot 列表中的 x 轴和 y 轴变量并打印绘图
【发布时间】:2017-12-06 22:48:54
【问题描述】:

我通过了这个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]]))
  }

【问题讨论】:

    标签: r plot ggplot2


    【解决方案1】:

    这个呢?

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-08
      • 2022-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多