为什么我不能用 ggplots 添加趋势线?

问题描述 投票:0回答:1

我正在自学 R,我想预测 2023 年、2024 年和 2025 年的指数增长。我的数据是 (data.growth) :

   Year Articles
1  2005   1.0000
2  2006   3.0000
3  2007   2.0000
4  2008   3.0000
5  2009   9.0000
6  2010  14.0000
7  2011  16.0000
8  2012  18.0000
9  2013  32.0000
10 2014  40.0000
11 2015  49.0000
12 2016  34.0000
13 2017  50.0000
14 2018  42.0000
15 2019  60.0000
16 2020  59.0000
17 2021  94.0000
18 2022  76.0000

我使用以下代码:

model1 <- lm(log(Articles) ~ Year, data = data.growth)
summary (model1)

new_data <- data.frame(Year = c(2023, 2024, 2025))
predicted_values.exp <- exp(predict(model1, newdata = new_data))
predictions <- data.frame(Year = c(2023, 2024, 2025), Articles = predicted_values.exp)
predictions
data.growth.exp <- rbind(data.growth, predictions)

由此我获得了 2023 年、2024 年和 2025 年的预测值。我尝试用指数趋势线绘制它。

我使用了以下内容:

point.data <- seq(2005, 2025, 0.1)
point.values <- exp(predict(model1, list (Year = point.data)))
plot(data.growth.exp)
lines(point.data, point.values, lwd=2, col = "red", xlab = "Time (s)", ylab = "Counts")

这张图:

enter image description here

我得到了我想要的东西,但我试图使用

ggplot()
得到同样的东西。我尝试了以下方法:

library(ggplot2)
ggplot(data.growth.exp, aes(Year, Articles)) +
  geom_point() +
  geom_smooth(method = "nls" , formula = y ~ a * exp(b * x), se = FALSE, method.args = list(start = list(a = 1, b = 1)))

但我得到以下信息:

警告信息:

stat_smooth()
计算失败: 评估模型时产生缺失值或无穷大

我已经尝试尽我所能修改一切,但我并没有真正明白我做错了什么。正如我所说,我自学,我唯一的指导是教程和尝试过与我类似的事情的人。我试图理解它,但我不明白为什么使用 ggplot 如此困难。

r ggplot2 graphics
1个回答
0
投票

也许我误解了这背后的数学原理。但为什么是

y ~ a * exp(b * x)
而不是
y ~ exp(a + b * x)

考虑到

model1
log(y) ~ a + b * x
所以在
nls()
中它应该是
y ~ exp(a + b * x)

geom_smooth(method = "nls" , formula = y ~ exp(a+b * x), se = FALSE, method.args = list(start = list(a = 1, b = 0)))
反而有效。

© www.soinside.com 2019 - 2024. All rights reserved.