我在R中有一个模型,在该模型中,我根据本田思域的行驶里程进行了回归:
civic <- read.csv("civic.csv")
c <- civic
plot (c$Mileage, c$Price,
xlab = "Mileage",
ylab = "Price")
regrPM1 <- lm(Price~Mileage, data = c)
abline (regrPM1, col="red",lwd=3)
这给了我以下内容:
到目前为止一切顺利。现在我有另一个模型:
regrPM2 <- lm(log(c$Price)~c$Mileage)
我想从上方将对应的回归线添加到Plot1中。 当我使用abline命令时:
abline(regrPM2, col="green", lwd=3)
其结果如下图所示:
现在这不能用于比较两个模型。我正在寻找一种不使用“对数”标度来比较它们的方法。 我认为,我可以使用曲线需求来获得更好的结果,但这还没有解决。
感谢您的任何帮助!
答案 0 :(得分:2)
这不是原始比例的直线。您可以按照以下步骤进行操作,以原始比例显示非线性预测。
DF <- data.frame(Mileage=seq(1, 150000, 1))
pred <- predict(regrPM2, newdata=DF)
lines(DF$Mileage, exp(pred))
必须在使用plot()
答案 1 :(得分:2)
在没有数据的情况下很难证明这里出了什么问题,所以我将尝试创建一些与您的大致相似的东西:
set.seed(69)
m <- rgamma(5000, 2, 2) * 30000
p <- 3e4 * log((rnorm(5e3, 1e4, 1e3) + m)/(m + rnorm(5e3, 5e3, 5e2)) + rgamma(5000, 2, 2)/8)
c <- data.frame(Mileage = m, Price = p)
plot (c$Mileage, c$Price,
xlab = "Mileage",
ylab = "Price")
为了演示目的,这已经足够近了。
现在,我们可以使用您的代码添加线性回归线:
regrPM1 <- lm(Price~Mileage, data = c)
abline (regrPM1, col="red",lwd=3)
现在,如果我们将里程数的价格对数进行回归,则与使用abline
绘制结果时得到的绿线相同:
regrPM2 <- lm(log(c$Price)~c$Mileage)
abline(regrPM2, col="green", lwd=3)
那是因为我们在(非记录)图上绘制价格的对数。我们想对回归结果进行反对数并作图。
请注意,最好在我们的data
调用中使用lm
参数,所以我们开始做吧:
regrPM3 <- lm(log(Price) ~ Mileage, data = c)
现在,与其尝试将其绘制为一条直线,不如以固定间隔获取其预测的对数并绘制它们:
lines(seq(0, 2e5, 1e3),
exp(predict(regrPM3, newdata = list(Mileage = seq(0, 2e5, 1e3)))),
col = "blue", lty = 2, lwd = 4)
所以蓝色虚线是对数回归的样子。