微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

我有 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,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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。