我在尝试使用不同数量的面板在 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)
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)
图像被缩放以在堆栈溢出时显示,但正如您从设备调用中看到的那样,它们的大小完全相同。
这个问题让我很困惑,老实说感觉像是一个错误,但是我知道 R 绘图代码非常成熟,所以我希望有一个解决方案。
我继承了一些使用我认为是库的常见 R 习惯用法的代码,但我不确定以如此冗长的方式编写会实现什么。最终我打算重写,但在我做一些愚蠢的事情之前,我首先想知道为什么。
ecd <-
function(formula, data, subset, weights, offset, ...) {
cl = match.call()
mf = match.call(expand.dots = FALSE)
m =
match(c("formula", "data", "subset", "weights", "offset"),
names(mf),
0L)
mf = mf[c(1L, m)]
mf$drop.unused.levels = TRUE
mf[[1L]] = quote(stats::model.frame)
mf = eval(mf, parent.frame())
mt = attr(mf, "terms")
y = stats::model.response(mf, "numeric")
w = as.vector(stats::model.weights(mf))
offset = as.vector(stats::model.offset(mf))
x = stats::model.matrix(mt, mf, contrasts)
z = ecd.fit(x, y, w, offset, ...)
Run Code Online (Sandbox Code Playgroud)
我目前的理解是,它从函数的原始参数构造一个函数调用对象(类型?),然后手动调用它,而不是直接调用stats::model.frame。任何见解将不胜感激。