2014-10-01 75 views
0

我一直在与这个问题争斗一段时间了。我想使用grid.arrange减少ggplot和表格之间的空间。我看着各种各样的threads,在网上搜索,尝试了各种各样的东西,但如果它们在一列中,我不能缩小两个地块之间的空间。 (是的,它需要是饼图,尽管表格提供了更好的信息)减少grid.arrange中两个地块之间的空间

这是我的示例代码。

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) 

其他类似的线程提供宽度的解决方案,但我找不到高度的文档。

+0

'heights = c(4,1)'; ggplot2中的饼图很奇怪,似乎很难完全删除空间 – baptiste 2014-10-01 17:27:30

+0

@baptiste是的,饼图在ggplot中是完全不可思议的。我会检查高度选项。谢谢 – karlos 2014-10-01 21:02:22

回答

1

您可以尝试使用grid包。请参阅下面的png输出示例。在这个 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() 

enter image description here

然而,由于tableGrob不允许关于字体的许多缩放选项,我会建议使用PDF代替,这是可扩展的,即使初始的图形是相当小的。 Cairo包在这方面做得很好。

干杯!

+0

虽然我不明白所有赋予视口的参数,但看起来像这样会起作用。有没有一个地方可以了解视口以及它们在这些包中的使用方式? – karlos 2014-10-01 21:04:06

+0

你可以尝试使用布局命令的'heights'参数(尤其是“4”)和最后一个视口中的''''参数。该布局指定两个绘图区域,一个用于绘图,另一个绘制区域(高度为4行)。 'y'参数向上重新定位表格(零是视口的底部,顶部是1;较大的值会使它更接近上图)。 – SimonG 2014-10-01 21:11:21

相关问题