【问题标题】:ggplot2 grid_arrange_shared_legend change number of columnsggplot2 grid_arrange_shared_legend 更改列数
【发布时间】:2015-10-21 10:25:14
【问题描述】:

我正在使用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 列。我尝试通过在grid_arrange_shared_legend 中将ncol=1 替换为ncol=3 来实现这一点。这会导致所有图都在左列中,而中间和右列为空(请参阅pdf2)。

如何实现 3 列图?

【问题讨论】:

  • 那个ncol=1就是把图和图例放在一列。要自己安排绘图,您需要将 ncol 参数传递给 arrangeGrob... 所以将该部分更改为 do.call(arrangeGrob, c(lapply(plots, function(x) x + theme(legend.position="none")), ncol=3))

标签: r pdf plot ggplot2


【解决方案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 在他的评论中提供了这个解决方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-12
    • 1970-01-01
    • 1970-01-01
    • 2016-01-16
    • 2013-10-27
    • 2015-07-11
    相关资源
    最近更新 更多