Set time formatting on a datetime index when plotting Pandas Series

孤街浪徒 提交于 2019-12-11 02:38:48

问题


I have a Pandas Dataframe with a DatetimeIndex with a monthly (M) frequency. However, when I plot a column from this Dataframe the labels on my plot show a date and time even though these bits are meaningless. How can I fix this so that a month is only displaying in YYYY-MM format?


回答1:


Make a small modification to your DateTimeIndex before plotting by converting them to PeriodIndex and providing a monthly frequency, like so -

a.index = a.index.to_period('M')  # Even a.index.astype('period[M]') works

Demo:

Consider a DF as shown:

idx = pd.date_range('2016/1/1', periods=10, freq='M')
df = pd.DataFrame(dict(count=np.random.randint(10,1000,10)), idx).rename_axis('start_date')
df

Old DateTimeIndex:

>>> df.index
DatetimeIndex(['2016-01-31', '2016-02-29', '2016-03-31', '2016-04-30',
               '2016-05-31', '2016-06-30', '2016-07-31', '2016-08-31',
               '2016-09-30', '2016-10-31'],
              dtype='datetime64[ns]', name='start_date', freq='M')

New PeriodIndex:

>>> df.index = df.index.to_period('M')
>>> df.index
PeriodIndex(['2016-01', '2016-02', '2016-03', '2016-04', '2016-05', '2016-06',
             '2016-07', '2016-08', '2016-09', '2016-10'],
            dtype='period[M]', name='start_date', freq='M')

Plot them:

df['count'].plot(kind='bar')
plt.show()



来源:https://stackoverflow.com/questions/41046630/set-time-formatting-on-a-datetime-index-when-plotting-pandas-series

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!