ggplot R中的指数拟合
exponential fit in ggplot R
我一直在尝试使用 ggplot 和 geom_smooth 将指数曲线拟合到我的数据中。我正在尝试复制类似问题的答案 ()
但不断收到以下错误消息:
> exp.model <-lm(y ~ exp(x), df)
Error in lm.fit(x, y, offset = offset, singular.ok = singular.ok, ...) :
NA/NaN/Inf in 'x'
我不明白这个错误,因为数据集中没有 NA/NaN/Inf 个值:
>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
设置数据:
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))
问题在于,对任何大于 709 的数字求幂得到的数字大于可作为双精度浮点值存储的最大值(约 1e308),因此会导致数字溢出。您可以通过移动 x
变量轻松解决此问题:
lm(y~exp(x),data=dd) ## error
lm(y~exp(x-1981),data=dd) ## fine
但是,您可以更轻松地绘制此模型的拟合值,如下所示:
library(ggplot2); theme_set(theme_bw())
ggplot(dd,aes(x,y))+geom_point()+
geom_smooth(method="glm",
method.args=list(family=gaussian(link="log")))
我一直在尝试使用 ggplot 和 geom_smooth 将指数曲线拟合到我的数据中。我正在尝试复制类似问题的答案 (
> exp.model <-lm(y ~ exp(x), df)
Error in lm.fit(x, y, offset = offset, singular.ok = singular.ok, ...) :
NA/NaN/Inf in 'x'
我不明白这个错误,因为数据集中没有 NA/NaN/Inf 个值:
>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
设置数据:
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))
问题在于,对任何大于 709 的数字求幂得到的数字大于可作为双精度浮点值存储的最大值(约 1e308),因此会导致数字溢出。您可以通过移动 x
变量轻松解决此问题:
lm(y~exp(x),data=dd) ## error
lm(y~exp(x-1981),data=dd) ## fine
但是,您可以更轻松地绘制此模型的拟合值,如下所示:
library(ggplot2); theme_set(theme_bw())
ggplot(dd,aes(x,y))+geom_point()+
geom_smooth(method="glm",
method.args=list(family=gaussian(link="log")))