2

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?

picture of problem

1 Answer 1

5

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

enter image description here

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

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.