如何在ggplot2中为指数型数据添加趋势线?
问题解决:geom_smooth拟合指数趋势线失败
错误原因
你的代码使用formula = y ~ exp(x)时,x是2014-2023这类大数值,exp(2014)会生成远超R数值范围的极大值,直接变为Inf,导致线性模型lm无法拟合,触发NA/NaN/Inf的错误。
解决方案
针对你的指数增长数据,提供两种可行的修正方式:
方式1:对年份做中心化处理
将年份减去起始值(如2014),缩小x的数值范围后再拟合指数模型:
library(ggplot2) data <- data.frame( year = 2014:2023, totglp = c(27, 73, 125, 225, 266, 368, 466, 820, 1383, 2167) ) # 中心化年份:减去起始年份2014 data$year_centered <- data$year - 2014 ggplot(data, aes(x = year, y = totglp)) + geom_point() + geom_smooth(method = "lm", formula = y ~ exp(x_centered), se = FALSE, aes(x_centered = year_centered))
方式2:对y做对数变换拟合线性模型
你的数据呈现指数增长特性,log(y)与x近似线性关系,拟合后可还原趋势线:
ggplot(data, aes(x = year, y = totglp)) + geom_point() + geom_smooth(method = "lm", formula = log(y) ~ x, se = FALSE)
也可以直接用带对数链接的广义线性模型拟合:
ggplot(data, aes(x = year, y = totglp)) + geom_point() + geom_smooth(method = "glm", formula = y ~ x, method.args = list(family = gaussian(link = "log")), se = FALSE)
以上两种方式都能避免数值溢出问题,拟合出符合数据趋势的曲线。
内容的提问来源于stack exchange,提问作者Preston Carey
相关产品推荐
相关产品推荐

