【问题标题】:Plotting Smoothed Time Series绘制平滑时间序列
【发布时间】:2020-12-21 06:41:14
【问题描述】:

我正在尝试在此处遵循本教程:https://rc2e.com/timeseriesanalysis(页面底部)并在同一图上绘制平滑时间序列和原始时间序列。我在下面模拟了一些数据,对其进行了平滑处理,然后尝试将其绘制出来。

library(dplyr)
library(KernSmooth)
library(ggplot2)

a = rnorm(2000,10,10)
    y = ts(a, frequency = 12)

gridsize <- length(y)
bw <- dpill(t, y, gridsize = gridsize)

lp <- locpoly(x = t, y = y, bandwidth = bw, gridsize = gridsize)
smooth <- lp$y

ggplot() +
  geom_line(aes(x = t, y = y)) +
  geom_line(aes(x = t, y = smooth), linetype = 2)

但是,似乎有一些问题。出现第一个错误:'x' must be atomic for 'sort.list', method "shell" and "quick"

谁能告诉我我做错了什么?

谢谢

【问题讨论】:

  • 将我的笔记本电脑留在工作中,但可能会猜测您应该在美学之前的geom_line() 调用中定义data =ggplot 喜欢知道 x 和 y 来自哪里。是bw吗?
  • 感谢您的回复!这里似乎有问题:> bw

标签: r ggplot2 time-series data-visualization


【解决方案1】:

您可以直接在 ggplot 中将平滑曲线拟合到时间序列。这是在geom_smooth 中使用gam 的示例:

library(ggplot2)

set.seed(1)
a <- cumsum(rnorm(2000, 0.1, 10))
t <- seq(as.Date("1854-06-01"), by = "1 month", length.out = 2000)

ggplot(data.frame(t, a), aes(t, a)) + 
  geom_point(size = 0.1, color = "orange2", alpha = 0.5) +
  geom_smooth(method = 'gam', formula = y ~ s(x, k = 30, bs = "cs"),
              fill = "orange", color = "orange4", linetype = 2) +
  theme_bw()

【讨论】:

  • 谢谢!你知道我的做法有什么问题吗?
  • @Noob 您使用的方法似乎不喜欢在 x 轴上给出日期时间值(您也使用了一个不存在的名为 t 的变量)。如果您将t 定义为t &lt;- seq_along(a),它应该可以工作
猜你喜欢
  • 2021-12-08
  • 2013-06-13
  • 1970-01-01
  • 2018-11-18
  • 1970-01-01
  • 1970-01-01
  • 2017-09-28
  • 2015-11-18
  • 1970-01-01
相关资源
最近更新 更多