【问题标题】:Reducing space between two plots in grid.arrange减少 grid.arrange 中两个图之间的空间
【发布时间】:2014-10-01 17:08:31
【问题描述】:

我一直在与这个问题作斗争一段时间。我想使用 grid.arrange 减少 ggplot 和表格之间的空间。我查看了各种threads,在网上搜索,尝试了各种方法,但如果它们在一列中,我无法减少两个图之间的空间。 (是的,它必须是饼图,但表格可以提供更好的信息)

这是我的示例代码。

fruits <- data.frame(Type = c("Oranges", "Apples"), Quantity = c(200, 500))
g <- ggplot(fruits, aes(x = factor(1), y = Quantity, fill = Type)) + geom_bar(position = "fill", stat = "identity", width = 1) + coord_polar(theta = "y") 
g <- g  + labs(x = NULL, y = NULL) +  theme(axis.ticks = element_blank(), axis.text = element_blank(), panel.background = element_rect(fill = "white", colour = "white"), legend.position = "none")
g <- g + theme(plot.margin = unit(c(0,0,0,0), "lines"))
gtablegrob <- tableGrob(fruits, show.rownames = FALSE, gpar.coretext = gpar(fontsize = 10), par.coltext = gpar(fontsize = 10), gpar.rowtext = gpar(fontsize = 10), gpar.corefill = gpar(fill = "white", col = "white")) 
grid.arrange(g, gtablegrob, nrow = 2)

另一个类似的线程提供了关于宽度的解决方案,但我找不到关于高度的文档。

【问题讨论】:

  • heights=c(4,1); ggplot2中的饼图很奇怪,完全去掉空格似乎很难
  • @baptiste 是的,ggplot 中的饼图很奇怪。我将检查高度选项。谢谢

标签: r ggplot2


【解决方案1】:

您可以尝试使用grid 包。有关 png 输出,请参见下面的示例。类似的问题已在this中提出 post.

library(ggplot2)
library(grid)

# layout
vp.layout <- grid.layout(nrow=2, ncol=1, heights=unit(c(1,4), c("null","lines")),
  widths=unit(1,"null") )

png("test.png", width=200, height=350)
# start drawing
grid.newpage()
pushViewport(viewport(layout=vp.layout, name="layout"))
# plot
pushViewport(viewport(layout.pos.row=1, layout.pos.col=1, name="plot"))
print(g, newpage=FALSE)
upViewport()
# table
pushViewport(viewport(layout.pos.row=2, layout.pos.col=1, name="table"))
pushViewport(viewport(y=unit(1.2,"npc"), name="tableloc"))
grid.draw(gtablegrob)
upViewport()
dev.off()

但是,由于 tableGrob 不允许有关字体的许多缩放选项,我建议改用 pdf,即使初始图形相当小,它也是可缩放的。 Cairo 包在这方面做得很好。

干杯!

【讨论】:

  • 虽然我不明白给视口的所有参数,但看起来这会起作用。有没有什么地方可以让我了解视口以及它们在这些包中的使用方式?
  • 您可以尝试使用布局命令的heights 参数(尤其是“4”)和最后一个视口中的 参数。布局指定了两个绘图区域,一个用于绘图,第二个(4 行高度)用于表格。 y 参数将表格向上重新定位(0 是视口的底部,1 是顶部;较大的值将使其更接近上图)。