通过面板右侧微调ggplot大小和图例位置

时间:2019-04-13 18:36:50

标签: r ggplot2

我希望将ggplots包含在文档中,该文档的主文本区域(一列)的宽度为130毫米,其右边为7毫米的空白,并带有注释区域(例如LaTex {{1} }。图例应放置在注释区域中。我面临的问题是面板的右边缘在此设置中很重要,因为它定义了主要内容的结尾(130毫米)和图例的开头(+7毫米)。我知道\mpar{}提供的大小调整选项,以及使用ggsave()定位图例。但是,我不完全了解其位置和尺寸(this questions提供了一些帮助)。

是否可以通过一种更详细的方式访问尺寸?还是更适合使用其他绘图软件包?

以红色标注相关尺寸的示例图(摘自this教程):

Example plot with relevant dimensions in red

1 个答案:

答案 0 :(得分:0)

即使对于单面板图来说,也有点麻烦,但是通过一些工作,您可以计算出正确的大小和视口,

library(ggplot2)
library(grid)

p <- qplot(1,1,color=1) + theme(plot.background = element_rect(fill=NA))
g <- ggplotGrob(p)

# get the width of guide and stuff on the right
id_guide <- g$layout$r[grep('guide',g$layout$name)]
gw <- convertWidth(sum(g$widths[id_guide:ncol(g)]), 'cm')

# make a new gtable with fixed panel width
g_fixed <- g
id_panel <- g$layout$l[grep('panel',g$layout$name)]
g_fixed$widths[id_panel] <- unit(130,'mm') - sum(g$widths[-(id_panel:ncol(g))])

grid.newpage()
# viewport smaller than device for illustration
vp <- viewport(width=unit(130,'mm'), height=0.8)
pushViewport(vp=vp)
grid.rect(gp=gpar(fill='gold',lty=2))
# within the current viewport, place fixed grob
g_fixed$vp <- viewport(x=0,width=unit(130,'mm')+gw, just = 'left')
grid.draw(g_fixed)

相关:Align panel.background instead of plot.background with document margins