2017-12-06 10 views
0

私はこのquestionを処理しましたが、x軸とy軸の両方をループすることができます。私は以下のように試しましたが、グリッドの各プロットは印刷されません: ありがとう!ggplotリストと印刷プロットの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

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) 

enter image description here

関連する問題