简体   繁体   English

Python将年中的某天转换为轴上的月份

[英]Python convert the day of year to month on an axis

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.我希望数据是每天的,但轴每个月都显示为“Jan”、“Feb”等。

At the moment I can get the daily data, BUT the axis is 1-366 (the day of the year).目前我可以获得每日数据,但轴是 1-366(一年中的一天)。

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.或者我可以将月轴设为 1、2、3 等(通过将索引更改为 df.index.month),但是数据是每月的。

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

以 0、50、100、150 等为轴的图形结果 - 显示日期而不是月份,如 Jan、Feb、Mar 等

This can be done using the xticks function .这可以使用xticks 函数来完成。 Simply add the following code before plt.show() :只需在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'))

It may be more straightforward to simply add a datetime index to your pivoted dataframe.简单地将日期时间索引添加到您的透视数据帧可能更直接。

df_pivot.index = pd.date_range(
    df.index.max() - pd.Timedelta(days=df_pivot.shape[0]),
    freq='D', periods=df_pivot.shape[0])

df_pivot.plot()
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
plt.show()

The resulting plot has the axis as desired:结果图具有所需的轴:

在此处输入图片说明

This method also has the advantage over the accepted answer of working irrespective of your start and end date.无论您的开始和结束日期如何,此方法都优于公认的工作答案。 For example, if you change your index 's end date to end='30-Jun-2018' , the axis adapts nicely to fit the data:例如,如果您将index的结束日期更改为end='30-Jun-2018' ,则轴会很好地适应数据:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM