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

标签 python matplotlib

我有一个简单的时间序列数据框('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

最佳答案

您可以根据年份和周数创建一列适当的日期时间:

# %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

关于python - 如何按周和年绘制时间序列数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52850910/

相关文章:

python - 条形图 xtick 标签的位置有不规则的空间

python - 在 seaborn.PairGrid 上绘制多个数据集作为不同颜色的 kdeplots

python - Matplotlib:随时间叠加多个二维箭袋图

python - 值错误: year is out of range pyplot

python - 在 selenium python 中通过 href 查找链接

python - 将 SSL 验证与 Tweepy 结合使用

python - 如何停止 Tornado 网络服务器?

python - 列表/矩阵未保存正确的值

python - 为什么我的卷积例程与 numpy 和 scipy 不同?

python - 循环中的 Pandas 子图