R:layout() 影响绘图区域的边距大小

Tar*_*nnn 5 plot r

我在尝试使用不同数量的面板在 R 中自动生成复合图形时遇到问题。当我的图中有 3 个或更多面板时,边距显着不同(在 1x3 图中较小),足以导致 R 错误地绘制标签并有损整体外观。

# plot empty plot with box around plot and figure
plot_box <- function() {
        plot(1, 1, type='n', bty='n', xaxt='n', yaxt='n', xlab='', ylab='')
        box(lwd = 6)
        box("figure", lwd=6, col='red')
}

png("box_test1.png", width=1000, height=500)
par(oma=c(0,0,0,0))
layout(t(1:2))
par(mar=c(3, 3, 3, 3))
plot_box()
par(mar=c(3, 3, 3, 3))
plot_box()
dev.off()
Run Code Online (Sandbox Code Playgroud)

box_test1.png

png("box_test2.png", width=1500, height=500)
par(oma=c(0,0,0,0))
layout(t(1:3))
par(mar=c(3, 3, 3, 3))
plot_box()
par(mar=c(3, 3, 3, 3))
plot_box()
par(mar=c(3, 3, 3, 3))
plot_box()
dev.off()
Run Code Online (Sandbox Code Playgroud)

box_test2.png

图像被缩放以在堆栈溢出时显示,但正如您从设备调用中看到的那样,它们的大小完全相同。

这个问题让我很困惑,老实说感觉像是一个错误,但是我知道 R 绘图代码非常成熟,所以我希望有一个解决方案。

小智 5

您正在使用 mar 设置边距,这是在线条方面,很难正确管理。

 ‘mar’ A numerical vector of the form ‘c(bottom, left, top, right)’
      which gives the number of lines of margin to be specified on
      the four sides of the plot.  The default is ‘c(5, 4, 4, 2) +
      0.1’.
Run Code Online (Sandbox Code Playgroud)

如果您改用 mai,您将获得一致的物理尺寸。

 ‘mai’ A numerical vector of the form ‘c(bottom, left, top, right)’
      which gives the margin size specified in inches.
Run Code Online (Sandbox Code Playgroud)

另请参阅 ?par 的这一点:

 The meaning of ‘character size’ is not well-defined: this is set
 up for the device taking ‘pointsize’ into account but often not
 the actual font family in use.  Internally the corresponding pars
 (‘cra’, ‘cin’, ‘cxy’ and ‘csi’) are used only to set the
 inter-line spacing used to convert ‘mar’ and ‘oma’ to physical
 margins.  (The same inter-line spacing multiplied by ‘lheight’ is
 used for multi-line strings in ‘text’ and ‘strheight’.)
Run Code Online (Sandbox Code Playgroud)