奇怪的abline行为

时间:2012-09-18 14:19:07

标签: r plot line time-series

我目前正在尝试绘制价格差价的时间序列,然后添加带回归的abline。目前这仅仅是一个AR(1),因为我想在开始之前获得情节。

数据来自.XLS 并在OpenOffice

中进行组织
Date - Price1 - Price 2 - NA.(Empty) 
01.01.1982 - 1.56 - 2.53 -  
[...]

我正在读这个

library(xlsx)
library(AER)
x<-read.xlsx("data.xlsx",1)

然后我像这样填充空列

x$NA.=(x$Price1-x$Price2)

所以我现在在内存中有一个表生成这个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

(在Date之前有一个索引列,我不需要它,因为我按日期绘制但是它在那里)

然后我做

plot(x$Date,x$NA.)

我得到了正确的情节。我已经修改了那个绘图命令以获得正确的网格,轴和日期和行等,但是即使上面的简单绘图版本我也存在问题,所以问题不在于我的编辑。

问题如下:

如果我现在尝试绘制一条线

abline(a=1,b=1,col="blue")

它不起作用。命令通过,但它没有显示一行。但是:

abline(a=1,b=0,col="blue")

按预期工作,并显示蓝色的水平线。

我遇到的问题是我想将回归对象输入到图中,例如像

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")

我想要做的是一个简单的AR来测试。回归按预期工作,但是abline不会产生输出。

我还试图在没有变量的情况下进行abline - 只有在b = 0时它才有效。我也尝试过做

plot(SPRC)

然后是任何类型的abline,但是没有一个显示或它变成垂直线(!)。只有当b = 0时,它才变为水平线。

我想这与数据对象或输入有关,但我真的迷失了为什么它不起作用。我还在Date对象上尝试了as.Date,但这并没有改变任何东西。所有其他绘图命令似乎都工作,如添加自定义网格,par,定位器文本,轴等。如果我开始一个干净的R会话并且几乎只输入上面的代码,就会出现问题。 我还尝试切换回归变量,a和b值,或绘图变量的顺序。它仍然无效

你能想象会出现什么问题吗?

编辑: 我刚检查了数据类型是否为typeof()。 typeof x是“list”,其他一切都是“double”,即使我做了x$Date<-as.Date(x$Date,"%d.%m.%Y")

EDIT2: 我继续将文件保存为csv并使用read.csv读取 然后我做了

plot(x$Price1)

abline(a=40,b=1)

它所做的就是产生一条略微顺时针旋转的垂直(!)线。 我的R坏了吗? enter image description here

(我意识到规模是关闭的 - 价差是大约0.但即使a = 40,线也是相同的)

1 个答案:

答案 0 :(得分:2)

x<- read.table(text="Date Price1 Price2 NA.
 28.08.1987  18.30  19.44 1.24
 31.08.1987  18.65  19.75 1.12", sep="", header=TRUE)
x$Date <- as.Date(x$Date, "%d.%m.%Y")

plot(x$Date, x$NA.)

enter image description here

我的区域设置是法语,因此x标签代表星期五到星期一。

# If we're trying to find the actual coordinates of some points on the plot
# here is what we find:
locator() 
$x
[1] 6449.495 6448.035 6450.967

$y
[1] 1.182379 1.186610 1.182908

# The x axis is running from 6448 to 6451 and here is the reason:

x$Date # Here is your date vector
[1] "1987-08-28" "1987-08-31"
as.numeric(x$Date) # And here it is converted in numerics
[1] 6448 6451 # Hence the values found on the plot with locator.

# The default origin for dates is the first of January, 1970
# 6448 is the number of days from that date to the 28th of August 1987.

# But you can still use regression tools:
lm(NA.~Date, data=x)->lmx
abline(lmx)  # YOu don't actually need to break your lm object into its coefficients, abline recognize lm objects.

enter image description here

# And the same works with package zoo
library(zoo)
x<- read.table(text="Date Price1 Price2 NA.
 28.08.1987  18.30  19.44 1.24
 31.08.1987  18.65  19.77 1.12
 01.09.1987  18.65  19.75 1.10", sep="", header=TRUE)
x$Date <- as.Date(x$Date, "%d.%m.%Y")
SPRC<-zoo(x$NA.,x$Date)
SPRC2<-lag(SPRC, -1)
SPRC<-SPRC[2:length(SPRC)]
LMO<-lm(SPRC ~ SPRC2)
plot(SPRC)
abline(LMO)

enter image description here