将polinomial曲线拟合到时间序列数据

时间:2015-06-17 10:39:02

标签: r ggplot2 time-series lm

我有一个时间序列图,每月文章频率为y轴。数据如下所示:

<div id="content" class="{{tab.directive}}"></div>
<div id="content" {{tab.directive}}></div>

我使用ggplot2绘制它:

     Count.V       Date      Month       Week       Year
2637       6 2006-01-02 2006-01-01 2006-01-02 2006-01-01
406        4 2006-01-03 2006-01-01 2006-01-02 2006-01-01
543        4 2006-01-04 2006-01-01 2006-01-02 2006-01-01
998        3 2006-01-05 2006-01-01 2006-01-02 2006-01-01
1400       4 2006-01-06 2006-01-01 2006-01-02 2006-01-01
2218       4 2006-02-01 2006-02-01 2006-01-30 2006-01-01
2792       6 2006-02-02 2006-02-01 2006-01-30 2006-01-01
2488      10 2006-02-03 2006-02-01 2006-01-30 2006-01-01
954        8 2006-02-04 2006-02-01 2006-01-30 2006-01-01
2622       3 2006-02-06 2006-02-01 2006-02-06 2006-01-01
2321      11 2006-02-07 2006-02-01 2006-02-06 2006-01-01
2452      10 2006-03-21 2006-03-01 2006-03-20 2006-01-01
2267       5 2006-03-22 2006-03-01 2006-03-20 2006-01-01
1408       3 2006-03-23 2006-03-01 2006-03-20 2006-01-01
2602       3 2006-03-24 2006-03-01 2006-03-20 2006-01-01
2489       5 2006-03-25 2006-03-01 2006-03-20 2006-01-01
2771       1 2006-03-27 2006-03-01 2006-03-27 2006-01-01

Time series plot

然而,当我尝试将多项式曲线拟合到数据时,例如,

MyPlot <- ggplot(data = df, aes(x = Month, y = Count.V)) + stat_summary(fun.y = sum, geom ="line") + scale_x_date(
labels = date_format("%m-%y"),
breaks = "3 months")

有些东西不能正常工作:

Time series graph with a polynomial curve (failed)

我做错了什么?

编辑: 添加了多个月的数据框部分:

MyPlot + stat_smooth(method = "lm", formula = y ~ poly(x, 3), size = 1)

1 个答案:

答案 0 :(得分:2)

尝试使用mean代替sum这样的

ggplot(data = df, aes(x = Month, y = Count.V)) +
    stat_summary(fun.y = mean, geom ="line")+
    stat_smooth(method = "lm", formula = y ~ poly(x, 3), size = 1) +
    geom_point()+
    scale_x_date(labels = date_format("%m-%y"), breaks = "3 months")