我目前正在处理一些水文数据,因此我使用pivot函数进行了一些分析。因此,水文年份确实是从10月到9月,我想用这种方式来绘制它们。那么,matplotlib中有没有一种方法可以改变我绘图中x轴的排序呢?
我的pivot函数如下所示:
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结束。有谁知道怎么去那里吗?
发布于 2019-09-24 20:19:03
您可以像这样定义新列:
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
发布于 2019-09-24 20:31:10
您可以使用pandas concat对数据帧重新排序,重置索引,并使用由reset_index()
(重新排序的索引)生成的列'index'
作为新的记号标签。
dd = pd.concat([df.loc[df.index[9:]], df.loc[df.index[:9]]]).reset_index()
ax = dd[dd.columns.drop('index')].plot()
ax.set_xticks(dd.index)
ax.set_xticklabels(dd['index'])
plt.xlabel("month")
plt.show()
你会得到这个:
https://stackoverflow.com/questions/58079701
复制相似问题