首页 > 解决方案 > Python - Matplotlib:绘制水文年的数据透视表

问题描述

我目前正在处理一些水文数据,因此我使用枢轴函数进行了一些分析。因此,水文年确实从 10 月到 9 月计算,我想以这种方式绘制它们。那么,matplotlib 中有没有办法改变我的情节中 x 轴的排序?

我的数据透视函数如下所示:

pv = pd.pivot_table(df_mb, index=df_mb.index.month, columns=df_mb.index.year, aggfunc='mean')

pv.MB

    2011        2012            2013
1   NaN         0.159587        0.119823
2   NaN         0.134704        0.129065
3   NaN         0.163604        0.156006
4   NaN         0.451304        0.260984
5   NaN         0.202280        0.286951
6   NaN         -0.656959       -0.266000
7   NaN         -1.000123       -1.284144
8   NaN         -1.477041       -0.694400
9   NaN         0.002894        -0.196538
10  0.186086    0.191084        0.307935
11  0.299759    0.451645        NaN
12  0.133154    0.048562        NaN

并为我提供了这样的情节: 枢轴图

所以,我希望我的情节的 x 轴从 10 开始,到 9 结束。有人知道如何到达那里吗?

标签: pythonpandasmatplotlib

解决方案


您可以像这样定义新列:

df['col'] = np.where(df.index.month < 10, df.index.year, df.index.year + 1)
df['idx'] = np.where(df.index.month < 10, df.index.month+3, df.index.month-9)

df.pivot_table(index='idx',columns='col', values='val', aggfunc='mean')

给出,例如:

col  2014  2015
idx            
1       8     7
2       8     3
3       6     6
4       2     4
5       8     3
6       7     7
7       2     6
8       1     1
9       5     3
10      4     5
11      4     8
12      5     4

推荐阅读