【问题标题】:nls fit works but fails inside geom_smoothnls fit 有效,但在 geom_smooth 内失败
【发布时间】:2020-01-10 01:09:56
【问题描述】:

我想使用 ggplot 将 nls 函数拟合到某些数据。 nls 函数在 geom_smooth() 外部使用时运行良好,但在内部失败。

代码:

library(ggplot2)

df <- structure(list(concentration = c(0, 0.5, 1.5, 4, 12, 35, 100), 
                     response = c(0.015, 0.03673, 0.07212, 0.1027, 0.1286, 0.1858, 0.1812)),
                class = "data.frame", row.names = c(NA, -7L))

df.fit <- nls(response ~ k0 + (ki*concentration/(KI + concentration)), df, start = list(k0 = 0.001, ki = 0.18, KI = 1))
coef(df.fit)

plot <- ggplot(df, aes(concentration, response))+
  geom_point()+
  geom_smooth(method = "nls", se = F, method.args = list(formula = response ~ k0 + (ki*concentration/(KI + concentration)), 
                                                         start = list(k0 = 0.001, ki = 0.18, KI = 1)))
plot

我错过了什么?

【问题讨论】:

    标签: r ggplot2 nls


    【解决方案1】:

    您不能使用字符向量指定 nls 适合 geom_smooth。从帮助文件中:

      method: Smoothing method (function) to use, accepts either a
              character vector, e.g. ‘"auto"’, ‘"lm"’, ‘"glm"’, ‘"gam"’,
              ‘"loess"’ or a function, e.g. ‘MASS::rlm’ or ‘mgcv::gam’,
              ‘stats::lm’, or ‘stats::loess’.
    

    您可以指定一个新的预测向量并使用geom_line 绘制它们:

    library(ggplot2)
    
    df <- structure(list(concentration = c(0, 0.5, 1.5, 4, 12, 35, 100),
                         response = c(0.015, 0.03673, 0.07212, 0.1027, 0.1286, 0.1858, 0.1812)),
                    class = "data.frame", row.names = c(NA, -7L))
    
    df.fit <- nls(response ~ k0 + (ki*concentration/(KI + concentration)), df, start = list(k0 = 0.001, ki = 0.18, KI = 1))
    coef(df.fit)
    df$pred <- predict(df.fit)
    
    plot <- ggplot(df, aes(concentration, response))+
      geom_point()+
      geom_line(aes(x = concentration, y = pred))
    plot
    

    【讨论】:

    • 这是最近的变化吗?我以前做过,旧脚本中的代码仍然运行良好。我还看到 Hadley Wickham 对某人的帖子发表了评论,他在 geom_smooth 中使用了 nls,他并没有说这是一个问题。
    【解决方案2】:

    抱歉,我很不好意思现在才问这个问题。我只需要将 geom_smooth 公式中的变量“响应”和“浓度”更改为“y”和“x”,如下所示。

    library(ggplot2)
    
    df <- structure(list(concentration = c(0, 0.5, 1.5, 4, 12, 35, 100), 
                         response = c(0.015, 0.03673, 0.07212, 0.1027, 0.1286, 0.1858, 0.1812)),
                    class = "data.frame", row.names = c(NA, -7L))
    
    df.fit <- nls(response ~ k0 + (ki*concentration/(KI + concentration)), df, start = list(k0 = 0.001, ki = 0.18, KI = 1))
    coef(df.fit)
    
    plot <- ggplot(df, aes(concentration, response))+
      geom_point()+
      geom_smooth(method = "nls", se = F, method.args = list(formula = y ~ k0 + (ki*x/(KI + x)), 
                                                             start = list(k0 = 0.001, ki = 0.18, KI = 1)))
    plot
    

    【讨论】:

      猜你喜欢
      • 2014-09-21
      • 1970-01-01
      • 2014-06-07
      • 2017-06-23
      • 1970-01-01
      • 2017-04-19
      • 1970-01-01
      • 2012-05-24
      • 1970-01-01
      相关资源
      最近更新 更多