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

R脚本看似正确却无法用ggplot2绘制拟合曲线,求解决及添加误差带

问题解决:拟合曲线绘制与误差带添加

原代码存在的问题

  1. 未定义变量m:拟合nls模型时引用了coef(m),但m未提前定义,导致模型无法正常拟合。
  2. stat_smooth参数错误:嵌套多层method.args格式无效;且nls方法无法直接通过se=TRUE生成误差带。

修正后的代码

# 读取数据
d <- read.csv("examplecurve.csv")

# 1. 获取nls模型起始值:通过对数变换拟合线性模型
lm_model <- lm(log(y) ~ log(x), data = d)
start_vals <- list(a = exp(coef(lm_model)[1]), b = coef(lm_model)[2])

# 2. 拟合非线性模型
nls_model <- nls(y ~ a*(x^b), start = start_vals, data = d)
summary(nls_model)

# 3. 生成带置信区间的预测数据
new_x <- seq(min(d$x), max(d$x), length.out = 100)  # 生成连续x序列
new_data <- data.frame(x = new_x)

# 获取预测值及标准误
preds <- predict(nls_model, newdata = new_data, se.fit = TRUE)
# 计算95%置信区间
new_data$y_fit <- preds$fit
new_data$y_lower <- preds$fit - 1.96 * preds$se.fit
new_data$y_upper <- preds$fit + 1.96 * preds$se.fit

# 4. 绘图(包含散点、拟合曲线和误差带)
library(ggplot2)
fontsize <- 12

ggplot(d, aes(x = x, y = y)) +
  geom_point(col = "black", fill = "grey", alpha = 0.8, shape = 21, size = 2) +
  # 添加拟合曲线
  geom_line(data = new_data, aes(y = y_fit), color = "blue", size = 0.5) +
  # 添加95%置信区间误差带
  geom_ribbon(data = new_data, aes(ymin = y_lower, ymax = y_upper), alpha = 0.2, fill = "blue") +
  # 主题设置
  theme(
    panel.background = element_rect(fill = 'transparent', colour = 'black'),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    axis.title.x = element_text(colour = "black", size = fontsize),
    axis.text.x = element_text(angle = 0, vjust = 0.5, colour = "black", size = fontsize),
    axis.title.y = element_text(colour = "black", size = fontsize),
    axis.text.y = element_text(angle = 0, vjust = 0.5, colour = "black", size = fontsize),
    legend.position = "none",
    legend.justification = c(1,1),
    legend.key = element_rect(fill = 'transparent'),
    legend.background = element_rect(fill = 'transparent'),
    legend.text = element_text(size = 12)
  )

说明

  • 起始值获取:通过对数变换将非线性模型转化为线性模型,得到可靠的起始参数,确保nls模型收敛。
  • 误差带生成:手动计算预测值的95%置信区间,通过geom_ribbon绘制误差带。若需要包含数据变异的预测区间,可使用investr包的predictNLS函数或通过模拟模型参数实现。

内容的提问来源于stack exchange,提问作者Agus camacho

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 19:10:28