首页 > 解决方案 > ggplot2 texashousing 数据平滑短期噪声

问题描述

我正在研究 Hadley Wickham 的 ggplot2 优雅图形数据分析第 11 章练习 11.3.1:

在这里,Wickham 试图删除数据中的每月趋势 - tidyverse 中的 txhousing:

deseas <- function(x, month) {
resid(lm(x ~ factor(month), na.action = na.exclude))
}

txhousing <- txhousing %>% 
  group_by(city) %>% 
  mutate(rel_sales = deseas(log(sales), month))

ggplot(txhousing, aes(date, rel_sales)) + 
  geom_line(aes(group = city), alpha = 1/5) + 
  geom_line(stat = "summary", fun.y = "mean", colour = "red")

在此处输入图像描述

但问题是:最终的图显示了整体趋势中有很多短期噪音。您如何进一步平滑这一点以专注于长期变化?由于我对时间序列不太熟悉,因此不知道如何平滑短期变化......有没有人可以帮助我?

谢谢!

标签: rggplot2statisticstime-series

解决方案


我们可以geom_smooth用来添加趋势线。loess是平滑方法之一。

ggplot(txhousing, aes(date, rel_sales)) + 
  geom_line(aes(group = city), alpha = 1/5) + 
  geom_line(stat = "summary", fun.y = "mean", colour = "red") +
  geom_smooth(method = "loess", se = FALSE)

在此处输入图像描述


推荐阅读