[英]How can I run a exponential regression in R with an annotated regression equation in ggplot?
我在下面创建了一个具有强线性关联的正常二元数据集:
#### Load Library ####
library(tidyverse)
#### Create Data ####
x <- rnorm(n=1000, mean=120, sd=15)
y <- 4*x + 5 + rnorm(n=1000, mean = 0, sd = 5)
df <- data.frame(x,y)
#### Plot ####
ggplot(df,
aes(x,y))+
geom_point()+
geom_smooth(method = "lm")
#### Run Regression ####
lm.xy <- lm(y~x,
data = df)
summary(lm.xy)
这给了我想要的,线性关系和适合的 model(R2 可以理解为 90% 以上):
我试图用这样的指数数据做同样的事情:
#### Create Exponential Data ####
x2 <- dexp(1:50, rate=.1)*1000
y2 <- dexp(1:50, rate=.8)*1000
df2 <- data.frame(x2,y2)
#### Plot ####
ggplot(df2,
aes(x=x2,
y=y2))+
geom_point()+
geom_smooth()
绘制这个,没有问题:
但是,我不确定如何通过回归来 model 这个。 如果我做典型的回归公式:
#### Run Regression ####
exp.reg <- lm(y2 ~ x2,
df2)
summary(exp.reg)
可以理解的是,它的 model 精度要低得多:
Residual standard error: 42.66 on 48 degrees of freedom
Multiple R-squared: 0.4305, Adjusted R-squared: 0.4187
F-statistic: 36.29 on 1 and 48 DF, p-value: 2.302e-07
此外,我尝试将回归方程标记为 plot:
ggplot(df2,
aes(x=x2,
y=y2))+
geom_point()+
geom_smooth()+
stat_regline_equation(aes(exp.reg))
但这给了我一个错误:
Error in `check_aesthetics()`:
! Aesthetics must be either length 1 or the same as the data (50): x
所以我的问题有两个部分。 首先,我如何正确使用 model 指数回归? 其次,如何将回归方程注释到 ggplot 上?
几点评论:
geom_smooth
的 geom_smooth 适合LOESS model 。 所以这可能不是你想要的。现在关于如何拟合 model:我们可以将线性 model 拟合到对数转换数据。
# Fit a linear model
fit <- lm(log(y2) ~ log(x2), data = df2)
# Create `data.frame` with predictions
df_predict <- data.frame(x2 = seq(min(df2$x2), max(df2$x2), length.out = 1000))
df_predict$y2_pred = exp(predict(fit, newdata = df_predict))
# Plot
ggplot(df2, aes(x = x2, y = y2)) +
geom_point() +
geom_line(data = df_predict, aes(y = y2_pred))
fit
系数为
summary(fit)$coefficients
# Estimate Std. Error t value Pr(>|t|)
#(Intercept) -30.15675 7.152374e-16 -4.216327e+16 0
#log(x2) 8.00000 2.848167e-16 2.808824e+16 0
#Warning message:
# In summary.lm(fit) : essentially perfect fit: summary may be unreliable
请注意警告,这是由于您从dexp
生成数据的方式(没有任何错误)。
还要注意 8.0 的斜率估计(在对数尺度上),这只是您的两个dexp
速率参数 0.8/0.1 的比率。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.