首页 > 解决方案 > 在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:我希望轴保持不变,即保持原始比例。

标签: rregressionlinear-regression

解决方案


模型与模型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 预测中得到的标准误差在对数尺度上是对称的。见这里


推荐阅读