如何在 R 中为图形的背景部分着色以指示感兴趣的时间段

How to colour background sections of graphs in R to indicate time periods of interest

我想在我的 R 图形背景中添加颜色 'chunks' 以突出显示嵌套周期。我的 x 轴以天为单位,所以我希望颜色设置为 'from-to' 某些天。 我已经创建了一个粗略的手动版本,说明我希望它如何在我的图表上显示(见图片),但我不确定如何在我的代码中实现它。理想情况下,我希望为不同的块使用不同的颜色,例如橙色代表一个时期,蓝色代表另一个感兴趣的时期,这也可以显示在右侧的图例中。我的数据是每天的距离,然后转换为标准偏差以作图。

下面的代码用于到 stdev 的距离,然后使用标准 plot() 函数绘图:

ig16 <- read.csv(file='ig16distance.csv')
ig16$stdDist <- (ig16$Distance - mean(ig16$Distance))/sd(ig16$Distance)
plot(ig16$stdDist, type = "o",col = "red", xlab = "Days", ylab = "Stdev", 
 main = "IG0016")

示例数据如下:

    Day   Distance
1     1  20.396078
2     2  21.540659
3     3   4.000000
4     4  16.492423
5     5  16.000000
6     6  34.000000
7     7  34.234486
8     8   0.000000
9     9   4.000000
10   10   0.000000
11   11   0.000000
12   12   0.000000
13   13   0.000000
14   14  22.203603
15   15   0.000000
16   16   0.000000
17   17   2.280351
18   18   2.280351
19   19   2.280351
20   20   2.280351

任何有关实现此代码的建议都将不胜感激!

既然你不提供数据,我就用一些简单的例子数据来说明。您可以在要突出显示的区域上绘制一些透明矩形。

kings = c(60, 43, 67, 50, 56, 42, 50, 65, 68, 43, 65, 34, 47, 34, 49, 
41, 13, 35, 53, 56, 16, 43, 69, 59, 48, 59, 86, 55, 68, 51, 33, 
49, 67, 77, 81, 67, 71, 81, 68, 70, 77, 56)

plot(kings, type = "o",col = "red", xlab = "", ylab = "Years", 
 main = "Kings")
polygon(x=c(5,5,15,15), y=c(0,100,100,0), col="#0000FF22", border=F)
polygon(x=c(25,25,35,35), y=c(0,100,100,0), col="#FF990022", border=F)