具有具有相同 ylimits 的不同轴的 par(new=TRUE) 叠加函数

Overlaying functions with par(new=TRUE) having different axes with same ylimits

我一直在尝试用相同的 ylim 值覆盖基本 R xyplots overtop barplots。 即使使用这个虚拟代码:

data(mtcars)

barplot(mtcars$mpg,
        ylim=c(0,40))

par(new=TRUE,xaxt="s",yaxt="s",bty="n");plot(20,20,ylim=c(0,40),pch=c(16))

最终结果是 y 轴歪斜,其中中点在 20 处对齐,但轴的所有其他值都更远,因为它们大于或小于 20。

任何人都可以解释为什么会发生这种情况以及我将来如何避免这种情况?

您要查找的是 par 函数的 yxas 参数。

documentation for xaxs(与 x 轴的 yaxs 相同):

The style of axis interval calculation to be used for the x-axis. Possible values are "r", "i", "e", "s", "d". The styles are generally controlled by the range of data or xlim, if given.

Style "r" (regular) first extends the data range by 4 percent at each end and then finds an axis with pretty labels that fits within the extended range.

Style "i" (internal) just finds an axis with pretty labels that fits within the original data range.

Style "s" (standard) finds an axis with pretty labels within which the original data range fits.

Style "e" (extended) is like style "s", except that it is also ensures that there is room for plotting symbols within the bounding box.

因为我们想要适应轴,我将使用内部样式:

data(mtcars)

barplot(mtcars$mpg,
        ylim=c(0,40))

par(new=TRUE,yaxs="i", xaxt="s",yaxt="s",bty="n");plot(20,20,ylim=c(0,40),pch=c(16))

输出: