2017-02-21 86 views
1

基於在兩個ggplot2圖形之間共享圖例 腳本(https://github.com/tidyverse/ggplot2/wiki/Share-a-legend-between-two-ggplot2-graphs)。我嘗試將結果合併爲TIFF,但它不起作用,因爲我得到一個白色的圖像,任何想法如何解決它?保存共享圖例ggplot2

腳本:

library(ggplot2) 
library(gridExtra) 
library(grid) 


grid_arrange_shared_legend <- function(..., ncol = length(list(...)), nrow = 1, position = c("bottom", "right")) { 

    plots <- list(...) 
    position <- match.arg(position) 
    g <- ggplotGrob(plots[[1]] + theme(legend.position = position))$grobs 
    legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]] 
    lheight <- sum(legend$height) 
    lwidth <- sum(legend$width) 
    gl <- lapply(plots, function(x) x + theme(legend.position="none")) 
    gl <- c(gl, ncol = ncol, nrow = nrow) 

    combined <- switch(position, 
        "bottom" = arrangeGrob(do.call(arrangeGrob, gl), 
              legend, 
              ncol = 1, 
              heights = unit.c(unit(1, "npc") - lheight, lheight)), 
        "right" = arrangeGrob(do.call(arrangeGrob, gl), 
              legend, 
              ncol = 2, 
              widths = unit.c(unit(1, "npc") - lwidth, lwidth))) 
    grid.newpage() 
    grid.draw(combined) 

} 


dsamp <- diamonds[sample(nrow(diamonds), 1000), ] 
p1 <- qplot(carat, price, data = dsamp, colour = clarity) 
p2 <- qplot(cut, price, data = dsamp, colour = clarity) 
p3 <- qplot(color, price, data = dsamp, colour = clarity) 
p4 <- qplot(depth, price, data = dsamp, colour = clarity) 
cP<- grid_arrange_shared_legend(p1, p2, p3, p4, ncol = 4, nrow = 1) 


ggsave ("E:/cP.tiff", cP, dpi=500) 
+0

根據[ggsave]的官方文檔(http://docs.ggplot2.org/0.9.2.1/ggsave.html),它一次只能保存一張圖片。但是,如果您遵循[教程](https://github.com/tidyverse/ggplot2/wiki/Share-a-legend-between-two-ggplot2-graphs);爲什麼不做最後一行,即'grid_arrange_shared_legend(p1,p2,p3,p4,ncol = 4,nrow = 1)' 'grid_arrange_shared_legend(p1,p2,p3,p4,ncol = 2,nrow = 2)'? **我很困惑,你到底想要什麼。** –

回答

2

grid_arrange_shared_legend函數不返回任何東西。讓它返回combined對象(gtable),它應該可以工作。

return(combined) 
+0

你能幫助我如何返回組合對象(gtable)嗎? – user2916044