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,Pandas。
答案 0 :(得分:0)
您可以根据年份和星期创建datetime
列,针对日期绘制'number_of_cases'
,然后使用mdates
设置x标记的格式。
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)