exponential fit in ggplot R
Asked Answered
K

1

2

I've been trying to fit an exponential curve to my data using ggplot and geom_smooth. I'm trying to replicate the answer to a similar problem (geom_smooth and exponential fits) but keep getting following error message:

> exp.model <-lm(y ~ exp(x), df)
Error in lm.fit(x, y, offset = offset, singular.ok = singular.ok, ...) : 
  NA/NaN/Inf in 'x'

I don't understand the error, as there is not NA/NaN/Inf values in the dataset:

>df
      x         y
1  1981  3.262897
2  1990  2.570096
3  2000  7.098903
4  2001  5.428424
5  2002  6.056302
6  2003  5.593942
7  2004 10.869635
8  2005 12.425793
9  2006  5.601889
10 2007  6.498187
11 2008  6.967503
12 2009  5.358961
13 2010  3.519295
14 2011  7.137202
15 2012 19.121631
16 2013  6.479928
Koph answered 12/12, 2016 at 13:20 Comment(3)
I've seen that post and tried to replicate the plot, but got the error message again..Koph
@nrussell you marked this post as duplicate, but I get an error message trying to replicate the answer in the referred post. I've clarified above.Koph
Exponentiating such large numbers will result in floating-point overflows. hint: try exp.model <-lm(y ~ exp(x-1981), df)Bethsaida
B
7

Set up data:

dd <- data.frame(x=c(1981,1990,2000:2013),
  y = c(3.262897,2.570096,7.098903,5.428424,6.056302,5.593942,
  10.869635,12.425793,5.601889,6.498187,6.967503,5.358961,3.519295,
  7.137202,19.121631,6.479928))

The problem is that exponentiating any number larger than about 709 gives a number greater than the maximum value storable as a double-precision floating-point value (approx. 1e308), and hence leads to a numeric overflow. You can easily remedy this by shifting your x variable:

lm(y~exp(x),data=dd) ## error
lm(y~exp(x-1981),data=dd) ## fine

However, you can plot the fitted value for this model more easily as follows:

library(ggplot2); theme_set(theme_bw())
ggplot(dd,aes(x,y))+geom_point()+
   geom_smooth(method="glm",
            method.args=list(family=gaussian(link="log")))
            
            
Bethsaida answered 12/12, 2016 at 19:48 Comment(2)
Thanks, this is pretty much what I was looking for!Koph
here's another example that may be of use hereFreeloader

© 2022 - 2024 — McMap. All rights reserved.