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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了按面板右侧微调ggplot大小和图例位置相关的知识,希望对你有一定的参考价值。

我喜欢在文档中包含ggplots,该文档的主文本区域(一列)的宽度为130毫米,接着是右边7毫米的边距和注释的区域(例如LaTex mpar{})。传说应该放在注释区域。我面临的问题是面板的右边缘在此设置中很重要,因为它定义了主要内容的末端(130毫米)和图例的开头(+ 7毫米)。我知道ggsave()提供的尺寸选项以及使用theme()定位传奇。但是,我并不完全了解定位和尺寸(this questions提供了一些帮助)。

有没有办法以更详细的方式访问维度或另一个绘图包更合适?

相关尺寸为红色的示例图(取自this教程):

Example plot with relevant dimensions in red

答案

它有点繁琐,即使对于单面板图,但通过一些工作,您可以计算正确的大小和视口,

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

以上是关于按面板右侧微调ggplot大小和图例位置的主要内容,如果未能解决你的问题,请参考以下文章

Chart.js:将标题/图例位置更改为右侧

如何在 ADF 中设置滚动条位置

可变大小图形的图例位置

带有片段的两个面板 UI 与单独的活动

如何限制图例大小并使其可使用饼图滚动?和 javafx 布局

如何使组件在面板的某个区域内居中