首页 > 解决方案 > R:绘制 lm() 预测值的 geom_line() 和几何平滑不重合

问题描述

我有以下数据

df <- data.frame(x= c(0,1,10,100,1000,0,1, 10,100,1000,0,1,10,100,1000), 
                 y=c(7,15,135,1132,6459,-3,11,127,1120,6249,-5,13,126,1208,6208))

在使用数据制作线性模型后,我使用该模型从已知的 x 值预测 y 值。将预测的 y 值存储在数据框“pred.fits”中

fit <- lm(data = df, y ~ x)

pred.fits <- expand.grid(x=seq(1, 2000, length=2001))

pm <- predict(fit, newdata=pred.fits, interval="confidence")

pred.fits$py <- pm[,1]

我绘制数据并同时使用 geom_smooth() 和 geom_line(),它们似乎非常吻合。

ggplot(df, aes(x=x, y=y)) + 
       geom_point() + 
       geom_smooth(method = lm, formula = y ~ x, se = FALSE, size=1.5) +
       geom_line(data=pred.fits, aes(x=x, y=py), size=.2)

在此处输入图像描述

但是,当我绘制相同的数据时,将轴设置为对数刻度时,两个回归差异很大。

ggplot(df, aes(x=x, y=y)) + 
       geom_point() + 
       geom_smooth(method = lm, formula = y ~ x, se = FALSE, size=1.5) +
       geom_line(data=pred.fits, aes(x=x, y=py), size=.2) + 
       scale_x_log10() + 
       scale_y_log10()

在此处输入图像描述

我在这里错过了什么吗?

更新

在@Duck 指出我正确的方向之后,我能够做到正确。问题是,我希望数据未转换,但轴转换为 log10 比例。这就是我能够做到的。

df2 <- df[df$x>=1,] # remove annoying warning msgs.

fit2 <- lm(data = df2, log10(y) ~ log10(x))

pred.fits2 <- expand.grid(x=seq(10^0, 10^3  , length=200))

pm2 <- predict(fit2, newdata=pred.fits2, interval="confidence")

pred.fits2$py <-  10^pm2[,1] # convert the predicted y values to linear scale

ggplot(df2, aes(x=x, y=y)) + 
geom_point() + 
geom_smooth(method = lm, formula = y ~ x, se = FALSE, size=1.5) +
geom_line(data=pred.fits2, aes(x=x, y=py), size=1.5, linetype = "longdash") + 
scale_x_log10() +
scale_y_log10()

在此处输入图像描述

感谢大家的帮助。

标签: rggplot2lm

解决方案


此代码对您的理解很有用(感谢@BWilliams 的宝贵评论)。您希望 x 和 y 采用对数比例,因此如果将线性模型与不同比例混合会弄乱一切。如果您想查看相似的比例,最好使用对数变量训练不同的模型,然后使用正确的值绘制它。这是一种我们构建对数模型然后绘制的方法(数据值作为一个或负数已被隔离在一个新的数据框中df2)。这里的代码:

第一个线性模型:

library(ggplot2)
#Data
df <- data.frame(x= c(0,1,10,100,1000,0,1, 10,100,1000,0,1,10,100,1000), 
                 y=c(7,15,135,1132,6459,-3,11,127,1120,6249,-5,13,126,1208,6208))

#Model 1 all obs
fit <- lm(data = df, y ~ x)
pred.fits <- expand.grid(x=seq(1, 2000, length=2001))
pm <- predict(fit, newdata=pred.fits, interval="confidence")
pred.fits$py <- pm[,1]
#Plot 1
ggplot(df, aes(x=x, y=y)) + 
  geom_point() + 
  geom_smooth(method = lm, formula = y ~ x, se = FALSE, size=1.5) +
  geom_line(data=pred.fits, aes(x=x, y=py), size=.2)

输出:

在此处输入图像描述

现在是日志变量的草图,请注意我们如何log()跨主要变量使用以及如何构建模型:

#First remove issue values
df2 <- df[df$x>1,]
#Train a new model
pred.fits2 <- expand.grid(x=seq(1, 2000, length=2001))
fit2 <- lm(data = df2, log(y) ~ log(x))
pm2 <- predict(fit2, newdata=pred.fits2, interval="confidence")
pred.fits2$py <- pm2[,1]
#Plot 2
ggplot(df2, aes(x=log(x), y=log(y))) + 
  geom_point() + 
  geom_smooth(method = lm, formula = y ~ x, se = FALSE, size=1.5) +
  geom_line(data=pred.fits2, aes(x=log(x), y=py), size=.2)

输出:

在此处输入图像描述


推荐阅读