r plot time series abline strange behavior

Viewed 78

I have an unusual problem. I want to create a abline for R time series plot. When I do that it always shifts by 1 month.

See below for a reproducible example:

library(datasets)
tsdata = window(datasets::AirPassengers,start=c(1956,1),end=c(1960,12))
plot(tsdata,type="o")
abline(v=(1956+5/12),col="red")

As you can see from the chart below, the abline is drawn in the June of 1956, not in May of 1956 as requested by command in abline in R code: v=(1956+5/12).

Not sure how to fix this?

enter image description here

3 Answers

If we want to change then convert to yearmon from zoo and to numeric

library(zoo)
p1 <- as.numeric(zoo::as.yearmon("1956/05/01", "%Y/%m/%d"))

Or it can be derived from time. As the frequency is 12, we can select the 5th element which would be for May of 1956

p1 <- time(tsdata)[5]
abline(v = p1, col="red")

-output

enter image description here

Similar to the comment, this is not a suitable minimum reproducible example as your code doesn't give me a red vertical line either.

Nevertheless, the solution is that plot.ts in this case has decimal years as the x-axis. Therefore, your v coordinate must be 1956 + (5/12), or 1956.417.

abline(v=1956.417,col="red")

You have 12 points(months) fitted in 1 year which is actually a numeric value. After adding 5/12 you also need to normalize it with 10/12.

tsdata = window(datasets::AirPassengers,start=c(1956,1),end=c(1960,12))
plot(tsdata,type="o")
abline(v=(1956 + 5/12 * 10/12),col="red")

enter image description here

Related