How to plot fitted model over observed time series
This is a really really simple question to which I seem to be entirely unable to get a solution. I would like to do a scatter plot of an observed time series in R, and over this I want to plot the fitted model.
So I try something like:
model <- lm(x~y+z)
plot(x)
line开发者_运维百科s(fitted(model))
But this just plots x with lines.
Thanks
I think you want abline(model)
here as in this example from the help page:
z <- lm(dist ~ speed, data = cars)
plot(cars)
abline(z) # equivalent to abline(reg = z) or
abline(coef = coef(z))
x <- rnorm(100)
y <- rnorm(100)
z <- rnorm(100)
model <- lm(x~y+z)
plot(x,type="l",col="green")
lines(fitted(model),col="blue")
I tried this and it seems to work
Another opportunity:
n = 100; mi = 0; sigma = 2
x = rnorm(n,mi,sigma)
e = rnorm(n,0,1)
b0 = 1; b1 = 2
y = b1*x + b0 + e
#plot observations
plot(x,y)
#model
lm_res= lm(y~x)
summary(lm_res)
arg= c(min(x),max(x))
out = coef(lm_res)[2]*arg+ coef(lm_res)[1]
#plot model line
lines(arg, out, col = 'red')
精彩评论