0

I would like to add a non-linear model line to a graph in R, but instead of letting ggplot find the best fit, I just want to preset its parameters and thus be able to see how multiple manually designed models fit on top of the data. I tried the following:

ggplot(cars, aes(x = speed, y = dist)) + 
geom_point() + 
geom_smooth(method = "nls", method.args = list(formula = y ~ 0.76*exp(x*0.5), color = blue, data = data)

But got the error:

Computation failed in 'stat_smooth()': formal argument "data" matched by multiple actual arguments

with slight adjustments, I also get the error 'what" must be a function or character string. Does anyone know if manually designating a line like this is possible? I could not find any other Stack Overflow post about this specific topic.

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
Cameron
  • 164
  • 14
  • Can you make your example reproducible by either sharing some sample data or using a built-in data set? – Gregor Thomas Sep 22 '21 at 14:17
  • But I think your issue may be that you shouldn't put `data = data` inside the `list()`. You probably don't need it at all since it's the same data for every layer, but if you do want to pass it again, put it in `geom_smooth()`, but not inside `list()`. – Gregor Thomas Sep 22 '21 at 14:19
  • As for finnding other StackOverflow posts about this topic, I got plenty when I searched the tags from your question, `[ggplot2] [nls]` as a search string. I'd recommend sorting by votes, and filitering to only include questions with answers. – Gregor Thomas Sep 22 '21 at 14:21
  • Thank you. I updated the code to include "cars" as the example table. Removing the data = and color = designations gives the following warning: Warning message: Computation failed in 'stat_smooth()': invalid first argument – Cameron Sep 22 '21 at 14:37

1 Answers1

2

You might be looking for geom_function():

gg0 <- ggplot(cars, aes(x = speed, y = dist)) +  geom_point()
gg0 + geom_function(fun = function(x) 0.76*exp(x*0.5), colour = "blue") +
     coord_cartesian(ylim=c(0,100))

I added coord_cartesian because the specified function attains really large values for the upper end of the x-range of this graph ...

cars data with exponential curve

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453