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

如何用ggplot绘制growthcurver包的SummarizeGrowth模型?predict函数失效

用ggplot绘制growthcurver拟合的生长曲线

growthcurver包的SummarizeGrowth返回的是自定义对象,直接调用predict()会失效,因为它不是标准的统计模型对象。要想用ggplot绘图,可通过两种方法生成拟合曲线数据:


方法一:调用内置nls模型生成预测值

gc_fit$fit是拟合过程中生成的nls模型对象,可直接用于预测:

library(growthcurver)
library(ggplot2)

# 加载数据并拟合模型
d <- growthdata
gc_fit <- SummarizeGrowth(d$time, d$A1)

# 提取原始观测数据
raw_data <- gc_fit$data

# 生成覆盖时间范围的平滑序列,用于绘制拟合曲线
new_time <- seq(min(d$time), max(d$time), length.out = 100)
# 生成预测值
predicted_data <- data.frame(
  time = new_time,
  predicted = predict(gc_fit$fit, newdata = list(time = new_time))
)

# ggplot绘图
ggplot() +
  geom_point(data = raw_data, aes(x = time, y = y), color = "black", size = 2) +
  geom_line(data = predicted_data, aes(x = time, y = predicted), color = "red", linewidth = 1) +
  labs(x = "时间", y = "吸光度(A1)", title = "生长曲线拟合") +
  theme_minimal()

方法二:手动用拟合参数计算预测值

从gc_fit$model中提取逻辑生长曲线的参数(k、r、n0),用公式直接计算:

library(growthcurver)
library(ggplot2)

# 加载数据并拟合模型
d <- growthdata
gc_fit <- SummarizeGrowth(d$time, d$A1)

# 提取原始观测数据
raw_data <- gc_fit$data

# 生成平滑时间序列
new_time <- seq(min(d$time), max(d$time), length.out = 100)
# 手动计算逻辑生长曲线预测值
predicted_data_manual <- data.frame(
  time = new_time,
  predicted = gc_fit$model$k / (1 + ((gc_fit$model$k - gc_fit$model$n0)/gc_fit$model$n0) * exp(-gc_fit$model$r * new_time))
)

# ggplot绘图
ggplot() +
  geom_point(data = raw_data, aes(x = time, y = y), color = "black", size = 2) +
  geom_line(data = predicted_data_manual, aes(x = time, y = predicted), color = "blue", linewidth = 1) +
  labs(x = "时间", y = "吸光度(A1)", title = "手动计算的生长曲线拟合") +
  theme_minimal()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 14:05:25