Reputation: 3582
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?
Upvotes: 2
Views: 1844
Reputation: 29711
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()
Upvotes: 5