加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python将轴上的年日期转换为月

发布时间:2020-12-17 17:35:22 所属栏目:Python 来源:网络整理
导读:我有一个想逐年绘制的时间序列.我希望数据是每日的,但轴将每个月显示为“ Jan”,“ Feb”等. 目前,我可以获取每日数据,但轴为1-366(一年中的一天). 或者我可以将月度轴设置为1、2、3等(通过将索引更改为df.index.month),但是数据为月度. 如何将一年中的日轴

我有一个想逐年绘制的时间序列.我希望数据是每日的,但轴将每个月显示为“ Jan”,“ Feb”等.

目前,我可以获取每日数据,但轴为1-366(一年中的一天).

或者我可以将月度轴设置为1、2、3等(通过将索引更改为df.index.month),但是数据为月度.

如何将一年中的日轴转换为月?或者我该怎么做?

显示每日数据的代码,但轴错误:

# import
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# create fake time series dataframe
index = pd.date_range(start='01-Jan-2012',end='31-12-2018',freq='D')
data = np.random.randn(len(index))
df = pd.DataFrame(data,index,columns=['Data'])

# pivot to get by day in rows,then year in columns
df_pivot = pd.pivot_table(df,index=df.index.dayofyear,columns=df.index.year,values='Data')
df_pivot.plot()
plt.legend(loc='center left',bbox_to_anchor=(1,0.5))
plt.show()

graph result with the axis of 0,50,100,150 etc - showing the day number not month as Jan,Feb,Mar etc

最佳答案
这可以使用xticks function完成.只需在plt.show()之前添加以下代码即可:

plt.xticks(np.linspace(0,365,13)[:-1],('Jan','Feb' ... 'Nov','Dec'))

或将以下名称包含在月份的中间:

plt.xticks(np.linspace(15,380,'Dec'))

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读