首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python - Matplotlib:绘制水文年份数据透视表

Python - Matplotlib:绘制水文年份数据透视表
EN

Stack Overflow用户
提问于 2019-09-24 19:50:39
回答 2查看 150关注 0票数 1

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

我的pivot函数如下所示:

代码语言:javascript
运行
复制
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结束。有谁知道怎么去那里吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-09-24 20:19:03

您可以像这样定义新列:

代码语言:javascript
运行
复制
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')

给予,例如:

代码语言:javascript
运行
复制
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
票数 3
EN

Stack Overflow用户

发布于 2019-09-24 20:31:10

您可以使用pandas concat对数据帧重新排序,重置索引,并使用由reset_index() (重新排序的索引)生成的列'index'作为新的记号标签。

代码语言:javascript
运行
复制
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()

你会得到这个:

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58079701

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档