基于共享两个ggplot2图表之间的图例 脚本(https://github.com/tidyverse/ggplot2/wiki/Share-a-legend-between-two-ggplot2-graphs)。我尝试将结果组合图保存为TIFF,但它不起作用,因为我得到一个白色图像,任何想法如何解决它?
脚本:
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 :(得分:2)
您的grid_arrange_shared_legend
功能无法返回任何内容。让它返回combined
对象(gtable),它应该可以工作。
return(combined)