Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to plot a lagged time series?

Tags:

r

ggplot2

I am trying to draw some quick graphs for exploratory analysis and have the following question:

How can I plot a lagged time series in ggplot? I am trying to do something like this:

 ggplot(data,aes(x=xdata,y=xdata-1)+geom_point()

But xdata-1 is subtracting 1 from xdata instead of reading the previous xdata value.

ggplot does not seem to have a lag.plot equivalent and I did find a function called gglagplot in the ggfortify package that seems to be exactly what I want but that is not available in the latest version of R (currently 3.2).

like image 976
qts Avatar asked Jun 06 '15 07:06

qts


1 Answers

You can use tail to get a lagged version a vector:

tail(x,-1)

But within ggplot2 aesthetics must either be length one or having the same length, so you should append a value to the lagged one in order to plot it against the original vector. For example:

x= 1:10
qplot(x=x,y=c(tail(x,-1),0))

Another option , is to use lag function from stats, but this assumes you are dealing with time series objects.

like image 118
agstudy Avatar answered Sep 30 '22 06:09

agstudy