You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R中实现指数回归并在ggplot中添加回归方程标注?

指数回归建模与可视化标注解决方案

1. 正确进行指数回归建模

指数关系的标准形式为 ( y = ae^{bx} ),这类非线性关系直接用lm()拟合线性模型精度极低,可通过两种方式处理:

方式一:对数变换转线性模型

对等式两边取自然对数,将非线性关系转为线性形式 ( \ln(y) = \ln(a) + bx ),再用lm()拟合:

# 构造示例指数数据集
set.seed(123)
x <- seq(1, 10, by = 0.5)
y <- 2 * exp(0.3 * x) + rnorm(length(x), 0, 0.5)

# 对数变换后拟合线性模型
log_lm_model <- lm(log(y) ~ x)
summary(log_lm_model)

# 还原指数模型参数
a_hat <- exp(coef(log_lm_model)[[1]])  # 将截距项ln(a)还原为a
b_hat <- coef(log_lm_model)[[2]]
# 最终指数方程:y = a_hat * exp(b_hat * x)

注意:若y包含0或负数,无法直接取对数,需改用下方非线性拟合方法。

方式二:直接非线性最小二乘拟合

用nls()函数直接拟合指数模型,需提供参数初始值(可根据数据趋势大致估计):

# 直接拟合非线性指数模型
nls_model <- nls(y ~ a * exp(b * x), start = list(a = 1, b = 0.1))
summary(nls_model)

2. 在ggplot中添加指数回归方程标注

方法一:手动计算标注(无需额外包)

基于对数变换后的线性模型,提取参数后用annotate()添加文本:

library(ggplot2)

# 生成方程和R²文本
eq_text <- paste0("y = ", round(a_hat, 2), " * e^(", round(b_hat, 2), "x)")
r_squared <- round(summary(log_lm_model)$r.squared, 2)
r_text <- paste0("R² = ", r_squared)

# 绘图并添加标注
ggplot(data.frame(x, y), aes(x, y)) +
  geom_point() +
  geom_smooth(method = "lm", formula = y ~ exp(x), se = FALSE, color = "blue") +
  annotate("text", x = max(x)*0.7, y = max(y)*0.3, 
           label = paste(eq_text, r_text, sep = "\n"), hjust = 0)

方法二:用ggpmisc包自动生成标注

借助ggpmisc的stat_poly_eq()直接生成指数方程和R²,需指定拟合方法与公式:

library(ggplot2)
library(ggpmisc)

ggplot(data.frame(x, y), aes(x, y)) +
  geom_point() +
  geom_smooth(method = "nls", formula = y ~ a * exp(b * x), 
              start = list(a = 1, b = 0.1), se = FALSE, color = "blue") +
  stat_poly_eq(
    formula = y ~ a * exp(b * x),
    aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~")),
    parse = TRUE, method = "nls", start = list(a = 1, b = 0.1),
    position = position_nudge(x = 2, y = 5)
  )

parse=TRUE会将文本解析为数学公式格式,position_nudge可调整标注位置。

内容的提问来源于stack exchange,提问作者Shawn Hemelstrand

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 20:48:22