Using abline () when the x axis is a date (i.e. Time Series Data)

I want to add some lines to the chart.

You usually specify abline(v=x-intercept) , but my x axis is in the form Jan-95 - Dec-09. How can I adapt the abline code to add a vertical line, for example, in February-95?

I tried abline(v=as.Date("Jan-95")) and other variations of this code snippet.

After that, you can add several vertical lines with one piece of code, for example Feb-95, Feb-97 and Jan-98?


An alternative solution could be to change my plot, I have a column with information of the month and a column with information of the year, how can I work with them to have a year on the X axis?

  example[25:30,] Year Month YRM TBC 25 1997 1 Jan-97 136 26 1997 2 Feb-97 157 27 1997 3 Mar-97 163 28 1997 4 Apr-97 152 29 1997 5 May-97 151 30 1997 6 Jun-97 170 
+6
source share
2 answers

First note: your YRM column is probably a factor, not a datetime, unless you manually changed it. I guess we donโ€™t want to do this, and our plot looks great with YRM as a factor.

In this case

 vline_month <- function(s) abline(v=which(s==levels(df$YRM))) # keep original order of levels df$YRM <- factor(df$YRM, levels=unique(df$YRM)) plot(df$YRM, df$TBC) vline_month(c("Jan-97", "Apr-97")) 

enter image description here

Disclaimer: this solution is a quick hack; It is neither universal nor scalable. For an accurate representation of datetime objects and extensible tools for them, see zoo and xts .

+5
source

I see two problems:

a) converting your data to a date / POSIX element and

b) the actual construction of vertical lines in certain lines.

First, create the correct date string, then use strptime() .

The second problem is solved by converting the POSIX date to a numeric value using as.numeric() .

 # dates need YMD example$ymd <- paste(example$Year, '-', example$Month, '-01', sep='') # convet to POSIX date example$ymdPX <- strptime(example$ymd, format='%Y-%m-%d') # may want to define tz otherwise system tz is used # plot your data plot(example$ymdPX, example$TBC, type='b') # add vertical lines at first and last record abline(v=as.numeric(example$ymdPX[1]), lwd=2, col='red') abline(v=as.numeric(example$ymdPX[nrow(example)]), lwd=2, col='red') 

Simple plot with dates on x-axis and vertical lines creating using abline

+2
source

All Articles