我可以将条形的 x 轴位置的“at”参数传递给 R 条形图吗?

机器算法验证 r 条形图
2022-04-09 17:57:31

嗨,在 R 中的基本图形中,我想在图表上叠加一个条形图,该图表在曲线上有不规则间隔的点。条形应代表自上一个样本以来这些点的变化。但我希望条形图与水平方向的点对齐,所以基本上应该有很多空白,并且折线图中的任何点都应该出现在相同的 x 轴位置,显示改变。条形的底部将从 x 轴(即 y=0)开始,或者可能在下方作为单独的图表。

我将如何在 R 中执行此操作?

我知道我可以用 bloxplots 做到这一点,正如您在下面的图表中看到的那样,方框与各个点对齐(仅供参考,南非政府债券)。现在如何添加条形图?

在此处输入图像描述

1个回答

barplot()只是 的包装器rect(),因此您可以自己添加条形图。这可能是一个开始:

x    <- sort(sample(1:100, 10, replace=FALSE)) # x-coordinates
y    <- log(x)                                 # y-coordinates
yD   <- c(0, 2*diff(y))                        # twice the change between steps
barW <- 1                                      # width of bars

plot(x, y, ylim=c(0, log(100)), pch=16)
rect(xleft=x-barW, ybottom=0, xright=x+barW, ytop=yD, col=gray(0.5))

在此处输入图像描述

您的第二个想法可以通过将设备区域拆分为par(fig).

par(fig=c(0, 1, 0.30, 1))                    # upper device region
plot(x, y, ylim=c(0, log(100)), pch=16)
par(fig=c(0, 1, 0, 0.45), bty="n", new=TRUE) # lower device region
plot(x, y, type="n", ylim=c(0, max(yD)))     # empty plot to get correct axes
rect(xleft=x-barW, ybottom=0, xright=x+barW, ytop=yD, col=gray(0.5))

在此处输入图像描述