如何在 geom_smooth() (来自 ggplot2 包)中为多个非线性回归分配不同的初始值?

How to assign different initial values inside geom_smooth() (from the ggplot2 package) for multiple nonlinear regressions?

我有 2 个数据集,一个用于 A 组,一个用于 B 组。我想在视觉上将数据拟合到 y=1-exp(-kx) 模型中。为此,我使用了 ggplot2 包和 geom_smooth() 函数。在 geom_smooth() 函数的参数中,有必要指明非线性拟合的初始值。由于我有 2 组数据,我想为每组分配不同的初始值。在这种情况下,对于 A 组,k 的初始值将为 0.45,而对于 B 组,则为 0.015。但是,我不知道该怎么做。有人可以帮助我吗?

library(ggplot2)


Group <- c("A", "B")
x <- 0:10
y <- c(0, 0.4, 0.6, 0.8, 0.9, 0.9, 0.95, 0.97, 0.98, 0.99, 1,
       0, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1)
start_values <- c(0.45, 0.015)

df <- expand.grid(x = x,
                  Group = Group)

df$y <- y

ggplot(data = df,
       aes(x = x,
           y = y)) +
  geom_point(aes(shape = Group,
                 color = Group)) +
  geom_smooth(aes(color = Group),
              formula = y ~ 1-exp(-k*x),
              method = "nls",
              method.args = list(k = start_values),
              se = FALSE)

据我所知,您无法使用 geom_smooth 轻松地为每个组传递不同的参数。一种选择是为每个组添加单独的图层

ggplot(data = df,
       aes(x = x,
           y = y)) +
  geom_point(aes(shape = Group,
                 color = Group)) +
  geom_smooth(aes(color = Group),
              formula = y ~ 1-exp(-k*x),
              method = "nls",
              method.args = list(start = c(k=start_values[1])),
              se = FALSE, data = function(x) subset(x, Group=="A")) + 
  geom_smooth(aes(color = Group),
              formula = y ~ 1-exp(-k*x),
              method = "nls",
              method.args = list(start = c(k=start_values[2])),
              se = FALSE, data = function(x) subset(x, Group=="B"))

您也可以使用 mapply 为您创建它们

,而不是为每个组手动添加图层
ggplot(data = df,
       aes(x = x,
           y = y)) +
  geom_point(aes(shape = Group,
                 color = Group)) +
  mapply(function(start, group) {
    geom_smooth(aes(color = Group),
          formula = y ~ 1-exp(-k*x),
          method = "nls",
          method.args = list(start = c(k=start)),
          se = FALSE, data = function(x) subset(x, Group==group))  
  }, start_values, c("A","B"))