R 保存共享图例ggplot2
基于两个ggplot2图形之间的共享图例 脚本()。我尝试将结果合并图保存为TIFF,但当我得到一张白色图像时,它不起作用,你知道如何解决吗 脚本:R 保存共享图例ggplot2,r,ggplot2,R,Ggplot2,基于两个ggplot2图形之间的共享图例 脚本()。我尝试将结果合并图保存为TIFF,但当我得到一张白色图像时,它不起作用,你知道如何解决吗 脚本: library(ggplot2) library(gridExtra) library(grid) grid_arrange_shared_legend <- function(..., ncol = length(list(...)), nrow = 1, position = c("bottom", "right")) { pl
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)
库(ggplot2)
图书馆(gridExtra)
图书馆(网格)
grid\u arrange\u shared\u legend您的grid\u arrange\u shared\u legend
函数不会返回任何内容。让它返回组合的
对象(gtable),它应该可以工作
return(combined)
根据的官方文件,它一次只能保存一张图像。但是,如果您遵循以下步骤:;你为什么不做最后几行,比如说,grid\u-arrange\u-shared\u-legend(p1,p2,p3,p4,ncol=4,nrow=1)
grid\u-arrange\u-shared\u-legend(p1,p2,p3,p4,ncol=2,nrow=2)
?我不知道你到底想要什么。你能帮我如何返回组合对象(gtable)吗?