如何按周和年绘制时间序列数据?

时间:2018-10-17 08:54:37

标签: python matplotlib

我有一个简单的时间序列dataframe('cats')。每年和每周的交易。我只想要一个以年和周为轴的折线图。

    year    week    transactions
0   2013    25      1824
1   2013    26      1876392
2   2013    27      2048913
3   2013    28      2060043
4   2013    29      1864779
5   2013    30      1844886
6   2013    31      2089084
7   2013    32      2017478
8   2013    33      1927819
9   2013    34      1965046

我可以在这行代码,但是它只能绘制vs索引

plt.plot(cats['total_sales'])

enter image description here

但是当我尝试添加轴时,会发生类似情况

plt.plot(cats['year'],cats['total_sales'])

enter image description here

2 个答案:

答案 0 :(得分:2)

您可以根据年份和星期编号创建一列正确的日期时间:

# %U assumes Monday as first day of the week. Use %W for Sunday
cats['week_yr'] = pd.to_datetime(cats['year'].astype(str) + ' ' + cats['week'].astype(str) + ' 1',
                                format='%Y %U %w')

那么您可以做:

cats.plot.line(x='week_yr', y='transactions')

并获得:

enter image description here

答案 1 :(得分:0)

使用plt.xticks

x = range(len(cats['total_sales']))
plt.plot(x, cats['total_sales'])
plt.xticks(x, zip(cats['year'], cats['week']))
相关问题