2017-02-21 10 views
1

2つの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)の公式文書によると、一度に1つの画像しか保存できません。ただし、[チュートリアル](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

関連する問題