Python将轴上的一年中的日期转换为月份 [英] Python convert the day of year to month on an axis

查看:187
本文介绍了Python将轴上的一年中的日期转换为月份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a time series that I would like to plot year on year. I want the data to be daily, but the axis to show each month as "Jan", "Feb" etc.

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

At the moment I can get the daily data, BUT the axis is 1-366 (the day of the year).

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

Or I can get the monthly axis as 1, 2, 3 etc (by changing the index to df.index.month), BUT then the data is monthly.

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

How can I convert the day of year axis into months? Or how can I do this?

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

Code showing the daily data, but the axis is wrong:

# 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()

推荐答案

可以使用 xticks函数.只需在plt.show()之前添加以下代码:

This can be done using the xticks function. Simply add the following code before plt.show():

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

或者以下内容使月份名称出现在月份的中间:

Or the following to have the month names appear in the middle of the month:

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

这篇关于Python将轴上的一年中的日期转换为月份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆