ggplot 边距 - 更改到轴的距离

ggplot margins - change distance to axis

我正在从基本的 R 绘图工具切换到 ggplot2,并且正在努力解决一个问题。

在基本 R 中,您可以通过设置边距来控制到四个轴(或 "box")中每一个的距离。结果边距是固定的,不取决于您绘制的内容。尽管刻度标签和轴标签的大小,这使我能够为我的论文生成具有完全相同绘图区域大小的绘图。

在 ggplot 中,我遇到了这个(最小工作示例):

library(ggplot2)
dat = data.frame(x = 1:5, y = 1e-5* (1:5) ^ 2)
p = ggplot(dat, aes(x, y)) + geom_point() + geom_line()

print(p)
print(p + scale_y_log10())

图左侧的黑色箭头显示我得到的实际边距之间的差异。轴标签 (y) 保持不变,而 y 轴的位置根据刻度标签(文本表示)的大小而变化。可以通过将 axis.text.y 更改为例如增加 size.

我想要的是无论绘制什么刻度标签都能够控制实际边距 - 在这种情况下,我可以实现不同数据集的相同尺寸的图形。

produce plots for my papers with exactly same plot area sizes

这可能有帮助:

grid::grid.draw(egg::set_panel_size(ggplot2::qplot(1,1), width = grid::unit(3, "in")))

虽然在 ggplot2 中有很多主题选项,但似乎没有为轴设置固定边距 space 的选项(或者如果有它隐藏得很好)。 cowplot 包有一个 align_plots 函数,可以对齐图表列表中的一个或两个轴。 align_plots returns 一个列表,其中的每个组件都是原始图,但指定的轴对齐。我正在使用 gridExtra 包中的 grid.arrange 函数来输出两个图,这样您就可以看到对齐的方式:

library(ggplot2)
dat = data.frame(x = 1:5, y = 1e-5* (1:5) ^ 2)
p = ggplot(dat, aes(x, y)) + geom_point() + geom_line()

print(p)

p1 = p + scale_y_log10()
print(p1)

library(cowplot)
library(gridExtra)
p2 = align_plots(p, p1, align = "hv")
grid.arrange(p2[[1]], p2[[2]])

这就是两个原始图的输出方式:

grid.arrange(p, p1)

遵循 Stewart Ross in , I ended up in the similar . I played around with grobs generated from my sample ggplots using 方法建议的方法 - 并且能够确定如何单独手动控制 grobs 的布局(至少在某种程度上)。

对于示例图,生成的 grob 布局如下所示:

> p1$layout
   t l  b r  z clip       name
17 1 1 10 7  0   on background
1  5 3  5 3  5  off     spacer
2  6 3  6 3  7  off     axis-l
3  7 3  7 3  3  off     spacer
4  5 4  5 4  6  off     axis-t
5  6 4  6 4  1   on      panel
6  7 4  7 4  9  off     axis-b
7  5 5  5 5  4  off     spacer
8  6 5  6 5  8  off     axis-r
9  7 5  7 5  2  off     spacer
10 4 4  4 4 10  off     xlab-t
11 8 4  8 4 11  off     xlab-b
12 6 2  6 2 12  off     ylab-l
13 6 6  6 6 13  off     ylab-r
14 3 4  3 4 14  off   subtitle
15 2 4  2 4 15  off      title
16 9 4  9 4 16  off    caption

这里我们对 4 轴感兴趣 - axis-l,t,b,r。假设我们想要控制左边距——寻找 axis-l。请注意,此特定 grob 的布局为 7x10。

p1$layout[p1$layout$name == "axis-l", ]
  t l b r z clip   name
2 6 3 6 3 7  off axis-l

据我了解,此输出意味着左轴采用一个网格单元格(#3 水平,#6 垂直)。注意索引 ind = 3。 现在,grob 中还有另外两个字段 - widthsheights。让我们转到 widths(它似乎是 gridunit 的特定列表)并使用我们刚刚获得的索引 ind 选择宽度。在我的示例中,输出类似于

> p1$widths[3]
[1] sum(1grobwidth, 3.5pt)

我猜它是 'runtime-determined' 一些 1grobwidth 的尺寸加上额外的 3.5pt。现在我们可以用另一个单位替换这个值(我测试了非常简单的东西,比如厘米或点),例如p1$widths[3] = unit(4, "cm")。到目前为止,我能够确认,如果您为两个不同图的左轴指定相等 'widths',您将获得相同的边距。

探索 $layout table 可能会提供其他控制绘图布局的方法(例如,查看 $layout$name == "panel" 以更改绘图区域大小)。