如何解决nlsLM非线性回归时持续出现的起始值警告问题
解决ggplot2中geom_smooth使用nlsLM时起始值被忽略的警告问题
问题原因
- 第一个警告
Ignoring unknown parameters: start:geom_smooth本身不支持直接传入start参数,你写在geom_smooth里的start会被直接忽略。 - 第二个警告:因为nlsLM没有接收到指定的起始值,只能默认将
a和b初始化为1,这才是你担心拟合偏差的根源。
解决方案
给nlsLM传递起始值必须通过geom_smooth的method.args参数,同时建议直接复用你之前手动拟合好的fitC5系数作为起始值,保证拟合结果和手动计算的一致。
修改后的完整代码
C5_abund <- read.csv(file = "C5_R.csv", sep=';') C5_abund2 <- C5_abund[C5_abund$Day <= 9.82, ] #exponetial regresion applied on theses point get_eqn <- function(fit) { eqn <- paste0("y = ", round(coef(fit)[1], 3), " * exp(", round(coef(fit)[2], 3), " * x)") return(eqn) } fitC5 <- nlsLM(C5 ~ a*exp(b*Day), data=C5_abund2, start=list(a=33804.52, b=0.5)) # using a= abundance at first day of experiment and b=theorical rate of growth eqnC5 <- get_eqn(fitC5) #y = 16470.994 * exp(0.525 * x) rss <- sum(resid(fitC5)^2) tss <- sum((C5_abund2$C5 - mean(C5_abund2$C5))^2) rsq2C5 <- 1 - (rss/tss) # rsq C5 : 0.9995 ggplot() + geom_point(data = C5_abund, aes(x = Day, y = C5),shape=16) + # 核心修改:将start参数放入method.args中传递给nlsLM geom_smooth(data = C5_abund2, aes(x = Day, y = C5), method = "nlsLM", formula = y ~ a * exp(b * x), se = FALSE, method.args = list(start = list(a = coef(fitC5)[1], b = coef(fitC5)[2])), size=0.5, linetype = "dashed", color="black") + annotate("text", x = 2, y =800000, label = "atop(y == 16470.994 * e ^ {0.525*x}, R ^ 2 == 0.9995 )", parse = TRUE, color = "black", size =4) + labs(title = "Abundance Dynamic of C5 culture over days", x = "Time (days)", y = "Cell concentration (cell/mL)") + theme_base()+ theme(legend.position = "bottom", plot.title = element_text(size = 14, hjust = 0.5), axis.title = element_text(size = 12), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), legend.background = element_rect(fill = "white", size = 0.5, linetype = "solid", color = "black"))
效果验证
修改后运行代码,两个警告都会消失:
method.args会把起始值正确传递给nlsLM,避免默认初始化1的问题;- geom_smooth不再收到未知参数,也不会抛出忽略参数的警告。
拟合出的曲线会和你手动计算的y = 16470.994 * exp(0.525 * x)完全一致,无需担心拟合准确性。
内容的提问来源于stack exchange,提问作者Marlexis
相关产品推荐
相关产品推荐

