如何解决这个练习?

时间:2018-06-30 09:15:01

标签: r ggplot2 statistics time-series

此练习来自 Hadley Wickham身份验证。 ggplot2用于数据分析的优雅图形

  

最终图显示了总体趋势中的许多短期噪声。   您如何才能进一步平滑以专注于长期变化?

最后的情节在这里。

library(tidyverse)
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")

enter image description here

此代码消除了季节性影响。

2000-2007年间持续增长, 下降到2010年(有些噪音),然后逐渐反弹。

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

您是只对图中的平滑线感兴趣还是在寻找平滑值?

如果只是在绘制之后,则可以使用geom_smooth函数:

ggplot(txhousing, aes(date, rel_sales)) +
  geom_line(aes(group = city), alpha = 1/5) +
  geom_smooth(stat = "smooth", colour = "red", method="auto")

或使用splines包中定义的公式来调用它。这使您可以调整自由度和分段多项式的度。

ggplot(txhousing, aes(date, rel_sales)) +
  geom_line(aes(group = city), alpha = 1/5) +
  geom_smooth(method = "lm", formula = y ~ splines::bs(x, df = 15, degree = 3), se = FALSE)
相关问题