r - 在ggplot中记录线性模型?
问题描述
数据来自: http: //www.principlesofeconometrics.com/poe5/poe5rdata.html,在文件中:collegetown.csv
对数线性模型的形式为:ln(y) = b1 + b2x
library(ggthemes)
library(ggplot2)
theUrl <- "../poedata/collegetown.csv"
collegetown <- read.csv(theUrl)
g1 <- ggplot(data = collegetown, aes(x = sqft, y = price))+
geom_point(col = "blue")
plot(g1)
logLinearModel <- lm(log(price)~sqft, data = collegetown)
g1 + geom_smooth(method = "lm", formula = y ~ exp(x), se = F, col = "green")+
theme_economist()
summary(logLinearModel)
如何绘制正确的曲线?我是否需要将预测值明确存储在数据框中?
PS:我希望轴保持不变,即保持原始比例。
解决方案
模型与模型y~exp(x)
不一样log(y)~x
,所以你没有得到你期望的更平滑。您可以使用以下代码指定平滑器是具有对数链接函数的广义线性模型:
g1 <- ggplot(data = collegetown, aes(x = sqft, y = price))+
geom_point(col = "blue")
g1 + geom_smooth(method = "glm", formula = y ~ x, se = F, col = "green",
method.args = list(family=gaussian(link="log"))) +
theme_economist()
这给了你想要的。如果这看起来不直观,您可以将 lm 放在绘图之外:
logLinearModel <- lm(log(price)~sqft, data = collegetown)
collegetown$pred <- exp(predict(logLinearModel))
ggplot(data = collegetown, aes(x = sqft, y = price))+
geom_point(col = "blue") +
geom_line(aes(y=pred), col = "green")+
theme_economist()
警告- 如果你想要标准错误,这两个版本是不一样的;第一种方法给出了对称误差,您可能从 lm 预测中得到的标准误差在对数尺度上是对称的。见这里。
推荐阅读
- flutter - 参数类型“Widget”不能分配给参数类型“PreferredSizeWidget?”
- python - 无法将yaml文件解析成python
- c++ - 如何将 pytorch 损失函数传递给 pytorch c++ 扩展中的 c++ 代码?
- java - 多个ID的android studio java映射功能
- python-3.x - ModuleNotFoundError:没有名为“matplotib”的模块
- python - 尝试将今天的日期与python中的自定义日期列表匹配
- .net - SignalR hubConnection.on 不工作。Clients.Others.SendAsync 和 hubConnection.on 沟通不畅
- php - Laravel - 验证语言环境不采用 {lang}.json 值
- mysql - 如何将特定行从一个表复制到另一个表
- vim - VIM 文件类型——为什么有些文件类型匹配器使用“call”而其他的使用“setf”?