我有一个简单的多项式回归,如下所示
attach(mtcars)
fit <- lm(mpg ~ hp + I(hp^2))
现在,我绘制如下图
> plot(mpg~hp)
> points(hp, fitted(fit), col='red', pch=20)
这为我提供了以下内容
我想要将这些点连接成一条平滑的曲线,使用直线可以得到以下结果
> lines(hp, fitted(fit), col='red', type='b')
我在这里错过了什么。我希望输出是一条连接这些点的平滑曲线
发布于 2014-04-28 14:59:40
尝试:
lines(sort(hp), fitted(fit)[order(hp)], col='red', type='b')
因为数据集中的统计单位是没有排序的,因此,当您使用lines
时,它会变得一团糟。
发布于 2014-04-28 15:32:15
我喜欢使用ggplot2
来实现这一点,因为添加数据层通常非常直观。
library(ggplot2)
fit <- lm(mpg ~ hp + I(hp^2), data = mtcars)
prd <- data.frame(hp = seq(from = range(mtcars$hp)[1], to = range(mtcars$hp)[2], length.out = 100))
err <- predict(fit, newdata = prd, se.fit = TRUE)
prd$lci <- err$fit - 1.96 * err$se.fit
prd$fit <- err$fit
prd$uci <- err$fit + 1.96 * err$se.fit
ggplot(prd, aes(x = hp, y = fit)) +
theme_bw() +
geom_line() +
geom_smooth(aes(ymin = lci, ymax = uci), stat = "identity") +
geom_point(data = mtcars, aes(x = hp, y = mpg))
https://stackoverflow.com/questions/23334360
复制相似问题