【问题标题】:Time series plot with week, year and number of hits具有周、年和点击次数的时间序列图
【发布时间】:2019-01-19 16:32:58
【问题描述】:
 In[1]    df    
Out[0]    week  year    number_of_cases
            8   2010    583.0
            9   2010    116.0
           10   2010    358.0
           11   2010    420.0
           ...   ...      ...
           52   2010    300.0
            1   2011    123.0
            2   2011    145.0

如何创建一个时间线图,其中我的 y 轴是病例数,我的 x 轴是增加与年份对应的周数? 我希望它从 2010 年的第 1 周到第 52 周,然后在 2011 年的第 1 周到第 52 周。并将其作为一张大图来查看每年的病例数如何随周而变化。

Python 3,熊猫。

【问题讨论】:

    标签: python python-3.x pandas time-series timeserieschart


    【解决方案1】:

    您可以根据年和周创建datetime 列,将'number_of_cases' 与日期相对应,然后使用mdates 格式化x-ticks。

    import pandas as pd
    import matplotlib.pyplot as plt
    import matplotlib.dates as mdates
    
    # Determine the date
    df['date'] = pd.to_datetime(df.assign(day=1, month=1)[['year', 'month', 'day']])+pd.to_timedelta(df.week*7, unit='days')
    
    # Plot
    fig, ax = plt.subplots()
    df.plot(x='date', y='number_of_cases', marker='o', ax=ax)
    
    # Format the x-ticks
    myFmt = mdates.DateFormatter('%Y week %U')
    ax.xaxis.set_major_formatter(myFmt)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 2014-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多