减少grid.arrange绘图之间的空间

11

我在这里提出了一个有关grid arrange的问题,并得到了很好的回答。现在我想减少图之间的间距,但却出现了错误。首先我将介绍有效的代码,然后是错误代码(我尝试过的)。我实际上找不到grid.arrange,并且一直认为它来自于gridExtra,但我可能是错误的。

所以有两个部分:

  1. 如何使用grid arrange减少图之间的间隔
  2. 在哪里可以找到grid.arrange的文档(Baptiste,我知道您维护gridExtra,请纠正我的思路或使用该程序包的方式,如果我没有按照预期使用该程序包。)

好的代码坏的间距

require(ggplot2);require(gridExtra)
A <- ggplot(CO2, aes(x=Plant)) + geom_bar() +
    coord_flip() + ylab("")
B <- ggplot(CO2, aes(x=Type)) + geom_bar() +coord_flip() 


 gA <- ggplot_gtable(ggplot_build(A))
 gB <- ggplot_gtable(ggplot_build(B))
 maxWidth = grid::unit.pmax(gA$widths[2:3], gB$widths[2:3])
 gA$widths[2:3] <- as.list(maxWidth)
 gB$widths[2:3] <- as.list(maxWidth)
 grid.arrange(gA, gB, ncol=1)

糟糕的代码(我的尝试)

require(ggplot2);require(gridExtra)
A <- ggplot(CO2, aes(x=Plant)) + geom_bar() +
    coord_flip() + ylab("") + theme(plot.margin= unit(1, "cm"))
B <- ggplot(CO2, aes(x=Type)) + geom_bar() +coord_flip() 


 gA <- ggplot_gtable(ggplot_build(A))
 gB <- ggplot_gtable(ggplot_build(B))
 maxWidth = grid::unit.pmax(gA$widths[2:3], gB$widths[2:3])
 gA$widths[2:3] <- as.list(maxWidth)
 gB$widths[2:3] <- as.list(maxWidth)
 grid.arrange(gA, gB, ncol=1)

错误:

Error in `[.unit`(theme$plot.margin, 2) : 
  Index out of bounds (unit subsetting)
2个回答

12

我误解了ggplot:

require(ggplot2);require(gridExtra)
A <- ggplot(CO2, aes(x=Plant)) + geom_bar() +
    coord_flip() + ylab("") + theme(plot.margin= unit(c(1, 1, -1, 1), "lines"))
B <- ggplot(CO2, aes(x=Type)) + geom_bar() +coord_flip() + 
    theme(plot.margin= unit(rep(.5, 4), "lines"))


 gA <- ggplot_gtable(ggplot_build(A))
 gB <- ggplot_gtable(ggplot_build(B))
 maxWidth = grid::unit.pmax(gA$widths[2:3], gB$widths[2:3])
 gA$widths[2:3] <- as.list(maxWidth)
 gB$widths[2:3] <- as.list(maxWidth)
 grid.arrange(gA, gB, ncol=1)

-3

是的, 文档上说: plot.margin | 绘图周围的边距(单位为顶部、右侧、底部和左侧边距的大小)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接