在时间序列图下放置形状

时间:2017-09-05 17:54:23

标签: r time-series

我有一个相对简单的情节,有两个形状和标签:

plot.ts(timeseries, xlab = "Week - Beginning in 2012", ylab = "Interest - 
Percentage of Max", 
lwd = 2, ylim = c(0, 120), xlim = c(0,250))
text(c(210, 115), c(105, 55), labels = c("Label 1", "Label 2"))
rect(200, 0, 220, 100, col = "green", density = 20)
rect(100, 0, 130, 50, col = "green", density = 20)

我已经找到了一种方法来获取时间序列图下的方框,但我对abline和panel.first都没有运气。

1 个答案:

答案 0 :(得分:2)

您只需要查看x轴和y轴,并为文本标签和框边选择合适的坐标。你一开始就弄错了,但是你可以玩它,直到它完美。

确保您已充分了解textrect中哪个参数对应于哪个坐标。有关图例,请参阅?text?rect

z <- ts(matrix(rt(200 * 8, df = 3), 200, 1),
        start = c(1961, 1), frequency = 12)

plot.ts(z, xlab = "Week - Beginning in 2012", ylab = "Interest - 
Percentage of Max")

text(c(1965, 1970), c(-5, -5), labels = c("Label 1", "Label 2"))
rect(1963, -6, 1967, -4, col = "green", density = 20)
rect(1968, -6, 1972, -4, col = "green", density = 20)

enter image description here

根据你刚刚留下的评论

  

我使用这些框将作为突出情节区域的一种方式    - 所以我需要在方框顶部显示的情节线,它将被着色。

我猜这是你想要的:

plot.ts(z, xlab = "Week - Beginning in 2012", ylab = "Interest - 
Percentage of Max")

text(c(1965, 1970), c(-5, -5), labels = c("Label 1", "Label 2"))
rect(1963, -1, 1967, 1, col = "green", density = 20)
rect(1968, -1, 1972, 1, col = "green", density = 20)

enter image description here

<强>更新

基于你刚刚留下的评论

  

我需要的是那条线在绿色框的前面,而不是   落后于它。

您想要的是在添加如下矩形之后用lines重新绘制线条:

plot.ts(z, xlab = "Week - Beginning in 2012", ylab = "Interest - 
Percentage of Max")

i <- .25*(0:20)
rect(1963+i, -6+i, 1967+i, -4+i, col = rainbow(11, start = 0.7, end = 0.1))
lines(z)

text(c(1970, 1975), c(-5, -5), labels = c("Boom", "How about that?"), col="red")

enter image description here