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)
根据[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)'? **我很困惑,你到底想要什么。** –