Adding a vertical line to a time series chart

Is it possible to use the abline () function and add a vertical line to the graph, where the x axis contains dates? I tried a lot of possible date formatting but can't make it work.

+4
source share
3 answers

Yes, the easiest way is to provide a Date object for abline :

 x <- as.Date("2013-05-27")+0:99 y <- cumsum(rnorm(100)) plot(x,y) abline(v=as.Date("2013-08-01")) 
+9
source

Adding James to the answer, in R. there are different date / time formats in R. Sometimes dates are saved in POSIX format and when you plot them abline with as.Date does not work.

In this case you should use

 abline(v = as.POSIXct("2013-08-01")) 
0
source

The x axis in the time series graph (plot.ts with the ts object) is in decimal form. For example, quarter 2, 2016 on the axis will be 2016.25

There is a lubridate package that has a function (decimal_date ()) that converts POSIXct dates and decimal dates that are accepted by abline (). Therefore, I take the date when I want to put a vertical line on the plot and put it in the "Date" form. Then I can put this in the decimal_date function and in abline

 install.packages("lubridate") library(lubridate) [YOUR PLOT CODE] date1 <- ymd("2013-08-01") abline(v=decimal_date(date1)) 
0
source

Source: https://habr.com/ru/post/1482972/


All Articles