在r中绘制正态分布的拟合线时的误差

时间:2019-06-23 06:11:42

标签: r

我尝试使用R中的lines()函数绘制正态分布的拟合线,但会产生错误。数据是SP500,我正在尝试比较SP500的对数收益分布与具有计算出的均值和标准差的正态分布。

SP500_R = diff(log(SP500['2008/2009']))

# compare the log return with normal distribution using dnorm function
mu = mean(SP500_R, na.rm=T)
sigma = sd(SP500_R, na.rm=T)

hist(SP500_R, nclass = 20, probability = TRUE)
lines(SP500_R, dnorm(SP500_R, mean = mu, sd = sigma), col='red', lend = 2)

我认为这是SP500_R中NA的问题,但事实证明这不是问题。删除SP500_R中的NA后,错误相同。重新启动R后,错误变为第二个错误。

我期望有一个带有直方图和红线的图,但是出现了这样的错误:

Error in plot.xy(xy.coords(x, y), type = type, ...) : 
  graphical parameter "lend" has the wrong length

重新启动R后的第二个错误:

Error in get(".xts_chob", .plotxtsEnv) : object '.xts_chob' not found

1 个答案:

答案 0 :(得分:0)

library(xts)

set.seed(12345)
SP500 <- xts(x=rnorm(500, mean=50), order.by=Sys.Date()-(1:500)*30)
SP500 ['2008/2009']

SP500_R = diff(log(SP500['2008/2009']))

head(SP500_R)
#                     [,1]
# 2008-01-22            NA
# 2008-02-21  0.0107095178
# 2008-03-22 -0.0337194554
# 2008-04-21 -0.0007512932
# 2008-05-21  0.0729341823
# 2008-06-20 -0.0757315444


# compare the log return with normal distribution using dnorm function
mu = mean(SP500_R, na.rm=T)
sigma = sd(SP500_R, na.rm=T)

#Remove first row and plot the result
lx <- as.numeric(SP500_R[-1])
hist(lx, nclass = 20, probability = TRUE)
lines(density(lx), col="red", lend=2, lwd=2)

enter image description here

使用dnorm()函数显示该行:

lx <- as.numeric(SP500_R[-1]) 
h<- hist(lx, nclass = 20, probability = TRUE) 
lines(sort(lx), dnorm(lx[order(lx)], mean = mu, sd = sigma), lend = 2, col='red', lwd=2) 

enter image description here

相关问题