我正在使用grid_arrange_shared_legend
,我发现here生成了一个图表网格。我稍微修改了grid_arrange_shared_legend
以满足我的需求:
grid_arrange_shared_legend <- function(plots) {
g <- ggplotGrob(plots[[1]] + theme(legend.position="bottom"))$grobs
legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]]
lheight <- sum(legend$height)
grid.arrange(
do.call(arrangeGrob, lapply(plots, function(x)
x + theme(legend.position="none"))),
legend,
ncol = 1,
heights = unit.c(unit(1, "npc") - lheight, lheight))
}
我将此功能称为
pdf("plots.pdf",width=12.21/2.54, height=20.92/2.54)
grid_arrange_shared_legend(plotList) #ncol=length(ns), main = "Main title")
dev.off()
这将生成一个包含4列图的pdf文件(请参阅pdf1)。但是,我需要3列代替。我尝试将ncol=1
替换为ncol=3
中的grid_arrange_shared_legend
来实现此目的。这导致所有绘图都在左列,中间和右列为空(请参阅pdf2)。
如何实现3列图?
答案 0 :(得分:1)
将grid_arrange_shared_legend
更改为
grid_arrange_shared_legend <- function(plots) {
g <- ggplotGrob(plots[[1]] + theme(legend.position="bottom"))$grobs
legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]]
lheight <- sum(legend$height)
grid.arrange(arrangeGrob(grobs=lapply(plots, function(x)
x + theme(legend.position="none")),ncol = 3),
legend,
ncol = 1,
heights = unit.c(unit(1, "npc") - lheight, lheight))
}
解决了这个问题。 user20650在他的评论中提供了这个解决方案。