幂律回归中stat_smooth和lm(使用对数)的R差?

问题描述 投票:2回答:2

我有一些数据。

library(ggplot2)    
x <-c(2600248.25,1303899.14285714,1370136.33333333,353105.857142857, 145446.952380952,299032,75142.2631578947,40381.1818181818,6133.93103448276,975.234567901235,779.341463414634)
    y <- c(4,7,6,14,21,9,19,22,29,81,41)

我想对其进行回归和绘制。我的问题是,我想对我的数据进行回归并绘制它,但是当我对对数值使用lm时,预测并绘制时,我得到的结果与stat_smooth不同。考虑到代码。

    fit0 <- lm(log(y) ~ log(x))
    summary(fit0)

    newx <- x
    lm.fit <- predict(fit0, newdata = data.frame(x=newx), interval = "confidence")
    df <- as.data.frame(cbind(x,y,lm.fit))

    p <- ggplot(df, aes(x,y)) + geom_point() + geom_smooth(method = "lm", formula ="y~x") + scale_x_log10() + scale_y_log10()

p <- p + geom_line(aes(y=fit)) # result too low
p <- p +  geom_line(aes(y=10^fit)) # result too high

如你所见,我试过用对数结果和用10^x转换回来的结果。就像现在一样,两个线性模型应该显示相同的值?这里有什么问题,我怎样才能得到正确的值?

我的最终目标是能够绘制预测区间)。

r ggplot2 regression linear-regression lm
2个回答
1
投票

你用的是 log10 秤上 ggplot 不过 log 的计算。在R中只使用 log() 意味着你使用的是自然对数。当你使用 log10() 相反,你看到的是没有区别的 geom_smoothlm. 由于 ggplot 只是叫 lm 例程,预计输出也是如此。

library(ggplot2)    
x <-c(2600248.25,1303899.14285714,1370136.33333333,353105.857142857, 145446.952380952,299032,75142.2631578947,40381.1818181818,6133.93103448276,975.234567901235,779.341463414634)
y <- c(4,7,6,14,21,9,19,22,29,81,41)

fit0 <- lm(log10(y) ~ log10(x))
summary(fit0)

newx <- x
fit <- predict(fit0, newdata = data.frame(x=newx), interval = "confidence")
df <- as.data.frame(cbind(x,y))

p <- ggplot(df, aes(x,y)) + geom_point() + geom_smooth(method = "lm", formula ="y~x") + scale_x_log10() + scale_y_log10()
p <- p +  geom_line(aes(y=10^fit[,1])) 
p

黑线和蓝线是重叠的,所以看不清。不过,这就是输出图。output


更多信息,请查看 文件.

log 计算对数,默认为自然对数。log10 计算常见的(即10基)对数,以及 log2 计算二进制(即二进制)对数。一般形式是 log(x, base) 用基数计算对数。


1
投票

运行这段代码,希望能回答你的问题。

制作模型

model=lm(y~x,df)

从我们所做的模型中预测出y值,并将其分配给预测出的

predicted<-predict(model,newdata = x.df)

使bothe的预测值和x的实际值的关系图成为

p<-ggplot(df, aes(x))+ scale_x_log10()+ geom_smooth(method='lm', aes(y=y), col='red')

这条线使实际值或原图

将预测点或数据添加到同一图形中。

p<- p+ geom_smooth(method='lm', aes(y=predicted), col='blue')

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.