R:使用带有基本图形的布局在上图和下图上匹配 x 轴刻度

R: Matching x-axis scales on upper and lower plot using layout with base graphics

我正在尝试将 3 个地块安排在一起。所有 3 个图都具有相同的 y 轴刻度,但第三个图的 x 轴比其他两个更长。我想在第一行并排排列前两个地块,然后将第三个地块放在第二行并与右侧对齐。理想情况下,我希望第三个图的 x 值在图 2 的整个范围内与图 2 对齐,然后在图 1 下方继续。我看过其他一些关于使用 layout 函数来达到此一般配置 (Arrange plots in a layout which cannot be achieved by 'par(mfrow =') 的帖子,但我还没有找到任何关于微调绘图以使比例匹配的信息。下面是一张蹩脚的图片,应该能够理解一般的想法。

我认为你可以通过使用 par("plt") 来做到这一点,其中 returns 绘图区域的坐标作为整个图形区域的一部分,以编程方式计算水平 space 分配到底部图。但即使使用这种方法,也需要手动调整。这是我现在得到的。

首先,将绘图页边距设置得比默认值窄一点。此外,las=1 将 y 轴标签旋转为水平,xaxs="i"(默认为 "r")将自动 x 轴填充设置为零。相反,我们将在创建绘图时设置所需的填充量。

par(mar=c(3,3,0.5,0.5), las=1, xaxs="i")

一些假数据:

dat1=data.frame(x=seq(-5000,-2500,length=100), y=seq(-0.2,0.6,length=100))
dat2=data.frame(x=seq(-6000,-2500,length=100), y=seq(-0.2,0.6,length=100))

创建布局矩阵:

# Coordinates of plot region as a fraction of the total figure region
# Order c(x1, x2, y1, y2)
pdim = par("plt")

# Constant padding value for left and right ends of x-axis
pad = 0.04*diff(range(dat1$x))

# If total width of the two top plots is 2 units, then the width of the 
#  bottom right plot is: 
p3w = diff(pdim[1:2]) * (diff(range(dat2$x)) + 2*pad)/(diff(range(dat1$x)) + 2*pad) + 
  2*(1-pdim[2]) + pdim[1]

# Create a layout matrix with 200 "slots"
n=200

# Adjustable parameter for fine tuning to get top and bottom plot lined up
nudge=2

# Number of slots needed for the bottom right plot
l = round(p3w/2 * n) - nudge

# Create layout matrix
layout(matrix(c(rep(1:2, each=0.5*n), rep(4:3,c(n - l, l))), nrow=2, byrow=TRUE))

现在创建图形:对 abline 的两次调用只是为了向我们展示图形的 x 轴是否对齐。如果不是,我们将再次更改 nudge 参数和 运行 代码。一旦我们得到了我们想要的布局,我们就可以最后一次 运行 所有代码而无需调用 abline

# Plot first two graphs
with(dat1, plot(x,y, xlim=range(dat1$x) + c(-pad,pad)))
with(dat1, plot(x,y, xlim=range(dat1$x) + c(-pad,pad)))
abline(v=-5000, xpd=TRUE, col="red")

# Lower right plot
plot(dat2, xaxt="n", xlim=range(dat2$x) + c(-pad,pad))
abline(v=-5000, xpd=TRUE, col="blue")
axis(1, at=seq(-6000,-2500,500))

这是我们用 nudge=2 得到的结果。注意图是排成一行的,但这也受到保存图(对于 png 文件)的像素大小的影响,我调整了大小以使上下图完全对齐。

我原以为按照相对于地块面积的比例(通过使用 par("plt"))铸造所有数量将确保上部和下部地块排成一行,并且它们将保持排列无论最终图像中的像素数量如何。但我一定是遗漏了一些关于基本图形如何工作的东西,或者我搞砸了计算(或两者)。无论如何,我希望这能帮助你得到你想要的情节布局。