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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With