I am currently trying to graph a time series of a price spread and then add an abline with a regression. Currently this is just a AR(1) because I wanted to get the plot right before starting.
The data is from a .XLS and is organized as such in OpenOffice
Date - Price1 - Price 2 - NA.(Empty)
01.01.1982 - 1.56 - 2.53 -
[...]
I am reading this as
library(xlsx)
library(AER)
x<-read.xlsx("data.xlsx",1)
then I fill the empty column like so
x$NA.=(x$Price1-x$Price2)
So I now have a table in memory that produces this head()
Date Price1 Price2 NA.
1 1987-08-28 18.30 19.44 1.24
2 1987-08-31 18.65 19.75 1.12
(there is an index column before Date, I don't really need it since I plot by date but its there)
I then do
plot(x$Date,x$NA.)
I get the correct plot. I have modified that plot command a bit to get correct grids, axis and dates and lines etc, but the problem I have also persists even with the simple plot version above, so the problem is not with my edits.
The problem is the following:
If I now try to plot a line
abline(a=1,b=1,col="blue")
It doesn't work. The command goes through, but it does not show a line. However:
abline(a=1,b=0,col="blue")
works as intended and shows a blue, horizontal line.
The problem I have is that I want to feed a regression object into the plot, for example like so
SPRC=zoo(x$NA.,x$Date)
SPRC2=lag(SPRC, -1)
SPRC=SPRC[2:length(SPRC)]
LMO<-lm(SPRC ~ SPRC2)
abline(a=LMO$coefficients[2],b=LMO$coefficients[1],col="red")
What I am trying to do is a simple AR to test things out. The regression works as intended, but the abline does not produce an output.
I also tried to do abline without variables - it works only if it b=0. I also tried instead to do a
plot(SPRC)
and then any kind of abline, but either none shows up or it becomes a vertical line (!). Only if b=0 it becomes a horizontal line.
I imagine this has to do with the data object or input, but I am really lost on why it does not work. I also tried an as.Date on the Date object, but that does not change anything. All other plot commands seem to work, like adding custom grids, par, locator texts, axis etc. The problem occurs if I start a clean R session and pretty much only enter the code above. I also tried to switch around the regression variables, the a and b values, or the order of the plot variables. It still does not work
Can you imagine what might be the issue?
Edit:
I just checked the datatypes if typeof().
typeof x is "list", everything else is "double", even if I do a x$Date<-as.Date(x$Date,"%d.%m.%Y")
Edit2: I went ahead and saved the file as csv and read it with read.csv then I did
plot(x$Price1)
and
abline(a=40,b=1)
All it does is produce a vertical(!) line that is slightly turned clockwise. Is my R broken?
(I realize the scale is off for the price - the spread is around 0. But even with an a=40, the line is identical)
abline(a=40, b=1)
means you're drawing the liney = 40x + 1
which (it seems to me) is indeed the line drawn on the graph you showed. – plannapus