"nls" ggplot2 中的模型,我做错了什么?结果没有意义

"nls" model in ggplot2, what am I doing wrong? Results not making sense

我正在尝试拟合“nls”模型,然后在 ggplot2 中绘制它并显示方程。情节看起来不错,我从模型中得到了方程式。

当我实际计算 y 应该有什么预测值时,我得到了非常虚假的答案,我做错了什么?这可能是我犯的数学错误。

library(tidyverse)

# creating df of interest
df = mtcars %>% select(hp, mpg)

# creating nls model
exp_model_coeff <- coef(nls(y ~ a * exp(b * x),
                            data = df, start = c(a = 36, b = -0.04)
))

# plotting smooth with model that was made
ggplot(data = df, aes(x = hp, y = mpg)) +
  geom_smooth(
    method = "nls", se = FALSE,
    formula = y ~ a * exp(b * x),
    method.args = list(start = c(a = 36, b = -0.003)),
    color = "black"
  ) +
  geom_point() +
  geom_text(
    x = 200, y = 30,
    label = as.expression(substitute(
      italic(y) == a %.% italic(e)^(b %.% x),
      list(
        a = format(unname(exp_model_coeff[1]), digits = 3),
        b = format(unname(exp_model_coeff[2]), digits = 3)
      )
    )),
    parse = TRUE
  )


# setting hp to test equation
hp_test = 200

# estimating mph based on hp_test
estimated_mpg = exp_model_coeff[1]*exp(exp_model_coeff[2]*hp_test)

# doesn't make any sense, as it should be around 15?
estimated_mpg

当我 运行 你提供的示例代码时,它给了我一个错误,无法计算 exp_model_coef 因为你对 nls 的调用使用了 y 和 x,但是有df 中没有名为 y 或 x 的列。我不得不将代码更改为:

exp_model_coeff <- coef(nls(mpg ~ a * exp(b * hp),
                            data = df, start = c(a = 36, b = -0.003)
))

当我 运行 它 estimated_mpg 是 15.376.

是否有可能在您的环境中定义了 x 和 y 并导致 exp_model_coeff 的错误值?