当起始值在不同的数据框中按类别分隔时,如何使用 geom_smooth 进行非线性回归?

How to do a non-linear regression using geom_smooth when start values are separated by category in a different data frame?

我有 2 个数据框:一个包含需要拟合到非线性模型的实验数据,另一个包含通过 nls 方法拟合的起始值。实验数据和初始值都分为 a 和 b 类。我想使用 ggplot2 制作一个图表,显示适合点并按类别分隔的曲线,但我无法指示每个类别的起始值,它们位于另一个数据框中。

在 MWE 中,我以两种方式显示具有起始值的数据框:1. 每列是一个类别,或 2. 每行是一个类别。 (参见 Constants1Constants2 对象)。我认为这个组织与调用 ggplot

中的值有关
library(ggplot2)

Category <- c("a", "b")
k1 <- c(10, 20)
k2 <- c(0.01, 0.02)

Constants1 <- data.frame(Category, k1, k2)

Constants2 <- data.frame(rbind(k1, k2))
colnames(Constants2) <- Category

x <- seq(0,100,20)
y <- c(0, 2, 3.5, 4.5, 5.5, 6,
       0, 7, 11, 14, 16, 17)

df <- expand.grid(x = x,
                  Category = Category)
df$y <- y

ggplot(data = df,
       aes(x = x,
           y = y)) +
  geom_point(aes(shape = Category)) +
  geom_smooth(aes(linetype = Category),
              formula = y ~ k1*(1-exp((-k2)*x)),
              method.args = list(start = list(k1 = ??, #Help here
                                              k2 = ??)),
              se = FALSE,
              method = "nls")

也许这就是您要找的。您可以为每个起始值组合添加一个,而不是只使用一个 geom_smooth。为此,我利用 purrr::pmap 循环遍历具有起始值的数据框,以创建 geom_smooth 层的列表,然后可以将其添加到 ggplot:

library(ggplot2)
library(purrr)

layer_smooth <- pmap(Constants1, function(...) {
  args <- list(...)
  geom_smooth(aes(linetype = Category),
              formula = y ~ k1*(1-exp((-k2)*x)),
              method.args = list(start = list(k1 = args$k1, #Help here
                                              k2 = args$k2)),
              se = FALSE,
              method = "nls")
})

ggplot(data = df,
       aes(x = x,
           y = y)) +
  geom_point(aes(shape = Category)) +
  layer_smooth