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

前端之家收集整理的这篇文章主要介绍了Python将轴上的年日期转换为月 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

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

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

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

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

  1. # import
  2. import pandas as pd
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5. # create fake time series dataframe
  6. index = pd.date_range(start='01-Jan-2012',end='31-12-2018',freq='D')
  7. data = np.random.randn(len(index))
  8. df = pd.DataFrame(data,index,columns=['Data'])
  9. # pivot to get by day in rows,then year in columns
  10. df_pivot = pd.pivot_table(df,index=df.index.dayofyear,columns=df.index.year,values='Data')
  11. df_pivot.plot()
  12. plt.legend(loc='center left',bBox_to_anchor=(1,0.5))
  13. 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()之前添加以下代码即可:

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

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

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

猜你在找的Python相关文章