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

Time:04-05

I'm trying to fit a "nls" model to then plot it in ggplot2 and show equation. The plot looks fine, and I get the equation from the model.

When I actually calculate what predicted value y should have I get pretty spurious answers, what am I doing wrong? It's probably a math error I'm making.

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

CodePudding user response:

When I ran the example code you provided, it gave me an error, and could not compute exp_model_coef because your call to nls uses y and x, but there are no columns named y or x in df. I had to change the code to:

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

When I ran it with that estimated_mpg was 15.376.

Is it possible that you have x and y defined in your environment and it is resulting in erroneous values for exp_model_coeff?

  • Related