2017-12-06 3 views
0

이 코드는 question을 통과했지만 x 축에서 반복됩니다. 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)) 
기능 오른쪽에 공통의 전설을 얻을 : 예를 들어

나는 dataframe이

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