繁体   English   中英

如何在ggplot图上添加指数回归方程和R2

[英]How to add the exponential regression equation and R2 on ggplot graph

我想知道如何用指数回归 model 拟合这些数据,以及如何在 ggplot 图上打印指数回归方程和 R2。 使用 geom_smooth() 来拟合数据会更好。 我找到了几种可能的解决方案,但仅适用于线性回归,而我对指数型回归很感兴趣。 这是我的代码:

library(ggplot2)

##### Creating the data frame
x <- c(0.54,0.59,0.57,0.54,0.10,0.07,0.17,0.24,0.51,0.57,0.55,0.52,0.40,0.43,0.45,0.43)
y <- c(156.9,234.8,191.9,203.2,59.8,36.0,87.2,23.8,168.7,182.3,155.8,205.1,101.2,115.5,118.8,159.1)
df <- data.frame(x, y)


##### Creating the plot
my_plot <- ggplot(data = df, mapping = aes(x, y)) + 
  geom_point()
my_plot

这是结果 plot:R图

任何帮助将不胜感激。

目前尚不清楚您期望回归采用何种形式。 我从数据的形状假设你想要回归 x 上的 y 的对数。

如果是这种情况,使用predict创建回归线并将方程文本构建为绘图表达式可能是最简单的。

这是一个完整的代表:

library(ggplot2)

x <- c(0.54, 0.59, 0.57, 0.54 ,0.10, 0.07, 0.17, 0.24, 
       0.51, 0.57, 0.55, 0.52, 0.40, 0.43, 0.45, 0.43)
y <- c(156.9, 234.8, 191.9, 203.2, 59.8, 36.0, 87.2, 23.8, 168.7,
       182.3, 155.8, 205.1, 101.2, 115.5, 118.8, 159.1)
df <- data.frame(x, y)

exp.mod    <- lm(log(y) ~ x, df)

new_x      <- seq(min(x), max(x), 0.01)
prediction <- exp(predict(exp.mod, newdata = list(x = new_x)))
exp_line   <- data.frame(x = new_x, y = prediction)

eq <- paste0('paste(y, " = ", italic(e^{',  round(exp.mod$coefficients[2], 2), 
             "*x ~~+~~ ", round(exp.mod$coefficients[1], 2),
             '}), ~~~~~~~~R^2~ "="~', round(summary(exp.mod)$r.squared, 2), ")")

my_plot <- ggplot(data = df, mapping = aes(x, y)) + 
  geom_point() +
  geom_line(data = exp_line) +
  geom_text(aes(x = min(x) + 0.1 * diff(range(x)), 
                y = min(y) + 0.9 * diff(range(y)), label = eq), 
            parse = TRUE, size = 5, check_overlap = TRUE, hjust = 0)

my_plot

代表 package (v0.3.0) 于 2020 年 7 月 21 日创建

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM