Search code examples
rggplot2nls

Add a manually designed non-linear line in ggplot2?


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.


Solution

  • 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