ggplot2 grid_arrange_shared_legend生成空图/页面

时间:2015-10-21 13:58:07

标签: r plot ggplot2 grid-layout

以下脚本

require(ggplot2)
require(gridExtra)

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))
}
plotList <- list()
df <- data.frame(value=rnorm(10))

for (i in 1:12){
  plotList[[i]] <- qplot(Sepal.Length, Petal.Length, data = iris, color = Species)
}
pdf("plots.pdf",width=12.21/2.54, height=20.92/2.54)
grid_arrange_shared_legend(plotList)
dev.off()

结果分为两页pdf。第一页是空的。第二页包含所需的图表网格。

为什么第一页是空的,我该如何摆脱它?

1 个答案:

答案 0 :(得分:1)

我不确定为什么第一页是空的。但是在onefile = FALSE中设置pdf可以解决问题。

pdf("plots.pdf",width=12.21/2.54, height=20.92/2.54,onefile=FALSE)

Stack Overflow中还有另一个与此问题相关的问题。 In R, how to prevent blank page in pdf when using gridBase to embed subplot inside plot

相关问题