在不同年份的Seaborn地块上叠加熊猫时间序列
问题描述:
我有熊猫数据框架,我想探索时间序列的周期性,趋势等。数据是Here。为了可视化它,我想在同一个图上叠加每个年份的“子时间序列”(即,从01/01/2000,01/01/2001和01/01具有相同的x坐标数据/ 2002)。在不同年份的Seaborn地块上叠加熊猫时间序列
我是否必须转换我的日期列以便每个数据具有相同的年份?
有没有人有如何做到这一点的想法?你可以做到这一点
答
设置
此分析,你链接
df = pd.read_csv(
'data.csv', sep=';', decimal=',',
usecols=['date', 'speed', 'height', 'width'],
index_col=0, parse_dates=[0]
)
我哈克
我剥夺了一切,但在t年度的数据他约会并假定2012
的年份,因为它是一个闰年,并将容纳2月29日。我splity一年分为多指数的另一个层面,unstack
和plot
idx = pd.MultiIndex.from_arrays([
pd.to_datetime(df.index.strftime('2012-%m-%d %H:%M:%S')),
df.index.year
])
ax = df.set_index(idx).unstack().speed.plot()
lg = ax.legend(bbox_to_anchor=(1.05, 1), loc=2, ncol=2)
在努力漂亮这件事
fig, axes = plt.subplots(3, 1, figsize=(15, 9))
idx = pd.MultiIndex.from_arrays([
pd.to_datetime(df.index.strftime('2012-%m-%d %H:%M:%S')),
df.index.year
])
d1 = df.set_index(idx).unstack().resample('W').mean()
d1.speed.plot(ax=axes[0], title='speed')
lg = axes[0].legend(bbox_to_anchor=(1.02, 1), loc=2, ncol=1)
d1.height.plot(ax=axes[1], title='height', legend=False)
d1.width.plot(ax=axes[2], title='width', legend=False)
fig.tight_layout()
答
一种方式是像这样所有年份创建一个共同的x轴:
df['yeartime']=df.groupby(df.date.dt.year).cumcount()
其中“yeartime”代表一年时间的小节数。接下来,创建一个年柱:
df['year'] = df.date.dt.year
现在,让我们的子集数据,将2000年,2001年1月1日,和2002年
subset_df = df.loc[df.date.dt.year.isin(['2000','2001',2002]) & (df.date.dt.day == 1) & (df.date.dt.month == 1)]
最后,绘制。
ax = sns.pointplot('yeartime','speed',hue='year',data=subset_df, markers='None')
_ =ax.get_xaxis().set_ticks([])