r - 如何为绘图上的每个因素添加回归线
问题描述
我创建了一个模型,我正在尝试添加适合数据的两个部分的曲线,即绝缘和无绝缘。我正在考虑将绝缘系数用作真/假术语,但我不确定如何将其转换为代码。条目 1:56 是“w/o”,而 57:101 是“w/”。我不确定如何包含我正在使用的数据,但这里是头部和尾部:
month year kwh days est cost avgT dT.yr kWhd.1 id insulation
1 8 2003 476 21 a 33.32 69 -8 22.66667 1 w/o
2 9 2003 1052 30 e 112.33 73 -1 35.05172 2 w/o
3 10 2003 981 28 a 24.98 60 -6 35.05172 3 w/o
4 11 2003 1094 32 a 73.51 53 2 34.18750 4 w/o
5 12 2003 1409 32 a 93.23 44 6 44.03125 5 w/o
6 1 2004 1083 32 a 72.84 34 3 33.84375 6 w/o
month year kwh days est cost avgT dT.yr kWhd.1 id insulation
96 7 2011 551 29 e 55.56 72 0 19.00000 96 w/
97 8 2011 552 27 a 61.17 78 1 20.44444 97 w/
98 9 2011 666 34 e 73.87 71 -2 19.58824 98 w/
99 10 2011 416 27 a 48.03 64 0 15.40741 99 w/
100 11 2011 653 31 e 72.80 53 1 21.06452 100 w/
101 12 2011 751 33 a 83.94 45 2 22.75758 101 w/
bill$id <- seq(1:101)
bill$insulation <- as.factor(ifelse(bill$id > 56, c("w/"), c("w/o")))
m1 <- lm(kWhd.1 ~ avgT + insulation + I(avgT^2), data=bill)
with(bill, plot(kWhd.1 ~ avgT, xlab="Average Temperature (F)",
ylab="Daily Energy Use (kWh/d)", col=insulation))
no_ins <- data.frame(bill$avgT[1:56], bill$insulation[1:56])
curve(predict(m1, no_ins=x), add=TRUE, col="red")
ins <- data.frame(bill$avgT[57:101], bill$insulation[57:101])
curve(predict(m1, ins=x), add=TRUE, lty=2)
legend("topright", inset=0.01, pch=21, col=c("red", "black"),
legend=c("No Insulation", "Insulation"))
解决方案
ggplot2
这比基础绘图要容易得多。像这样的东西应该工作:
ggplot(bill, aes(x = avgT, y = kWhd.1, color = insulation)) +
geom_smooth(method = "lm", formula = y ~ x + I(x^2), se = FALSE) +
geom_point()
在base
中,我将创建一个数据框,其中包含您要预测的点,例如
pred_data = expand.grid(
kWhd.1 = seq(min(bill$kWhd.1), max(bill$kWhd.1), length.out = 100),
insulation = c("w/", "w/o")
)
pred_data$prediction = predict(m1, newdata = pred_data)
然后用于lines
将预测添加到您的情节中。我的基本图形很生锈,所以如果你想要的话,我会把它留给你(或其他回答者)。
推荐阅读
- python - 如何使用 PyTesseract 从图像中提取单个字母?
- mysql - MySQL 以一对一关系插入行时出错 - (1452) 无法添加或更新子行:外键约束失败
- python - youtube 视频下载的暂停和恢复功能
- java - 为什么我的 CountDownTimer 似乎在倒退?
- python - Django:获取要在表单中使用的当前 URL 路径
- python - 除了琐碎的数据类型之外,python 不可变对象 id 是否相同?
- javascript - LayoutAnimation 在单击按钮时扩展所有列表 - React Native
- ssl - IIS 重写反向代理在使用 SSL 时出现 HTTP 502 错误
- django - Django 编辑模型的管理模板
- c++ - 如何正确总结两个列表?