Formatting xlabels datetime in matplotlib (pandas df.plot () method)

I cannot figure out how to change the format of these x-tags. Ideally, I would like to call strftime('%Y-%m-%d') on them. I tried things like set_major_formatter , but was unsuccessful.

 import pandas as pd import numpy as np date_range = pd.date_range('2014-01-01', '2015-01-01', freq='MS') df = pd.DataFrame({'foo': np.random.randint(0, 10, len(date_range))}, index=date_range) ax = df.plot(kind='bar') 

ugly x label formats

+7
python matplotlib pandas
source share
2 answers

The objects in date_range DF are Timestamp objects. Call Timestamp.strftime for each object:

 date_range = pd.date_range('2014-01-01', '2015-01-01', freq='MS') date_range = date_range.map(lambda t: t.strftime('%Y-%m-%d')) print date_range array([2014-01-01, 2014-02-01, 2014-03-01, 2014-04-01, 2014-05-01, 2014-06-01, 2014-07-01, 2014-08-01, 2014-09-01, 2014-10-01, 2014-11-01, 2014-12-01, 2015-01-01], dtype=object) 

This allows you to use more general formatting options or to trim the tag label string.

+6
source share

Just click the tag labels and change them:

 xtl=[item.get_text()[:10] for item in ax.get_xticklabels()] _=ax.set_xticklabels(xtl) 

enter image description here

+8
source share

All Articles