0

first time posting a question in here.

I can't seem to find an easy way to add an exponential trendline to my various scatterplots. I have 8 tree species with different relationships of their height (in meters) and its diameter at breast height (DBH for short in cm). For now I have managed to do the different scatter plots for each tree species, but I can't seem to find a way to add an exponential trendline. Scatter Plot of DBH - Height Relationship per Tree type

The code I used is as follows:

ggplot(data, aes(Height__m_,DBH__cm_)) +
  geom_point(aes(color = Species)) +
  facet_wrap(~Species, ncol = 4, nrow = 2) +
  labs(title = "DBH - Height Relationship", y = "Height (m)", x = "DBH (cm)")

When I add the geom_smooth function, I can't seem to add an exponential trendline since I know these types of relationships to be the best fit. The code I've tried using is:

 geom_smooth(method = "nls", formula =  y ~ a * exp(b * x), aes(color = "Exponential"),
          se = FALSE, start = c(a = 1, b= 1))`

If there's also a possibility of adding the R2 value, that would also be welcomed. I would appreciate the help!

markus
  • 25,843
  • 5
  • 39
  • 58
  • 1
    What output or errors did you get then you tried the `geom_smooth` function? – Jon Spring Feb 24 '21 at 08:31
  • Perhaps relevant: https://stackoverflow.com/a/41881894/6851825 – Jon Spring Feb 24 '21 at 08:39
  • There's around 17 warnings, but they all state the same: `Computation failed in `stat_smooth()`: number of iterations exceeded maximum of 50 14: In (function (formula, data = parent.frame(), start, control = nls.control(), ... : No starting values specified for some parameters. Initializing ‘a’, ‘b’ to '1.'. Consider specifying 'start' or using a selfStart model'` – Luis Figueroa Feb 24 '21 at 08:44

1 Answers1

2

We don't have your data, but here's an example using the built in Orange dataset. In this case, setting a lower starting b value of 0.001 removed a warning message (1: Computation failed in stat_smooth(): singular gradient that prevented finding any viable fits.

ggplot(Orange, aes(age,circumference)) +
  geom_point() +
  facet_wrap(~Tree, nrow = 2) +
  stat_smooth(method = 'nls', 
            method.args = list(start = c(a=1, b=0.001)), 
            formula = y~a*exp(b*x), colour = 'black', se = FALSE)

enter image description here

Jon Spring
  • 55,165
  • 4
  • 35
  • 53