16

I can't figure out how to change the format of these x-labels. Ideally, I'd like to call strftime('%Y-%m-%d') on them. I've 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

EdChum
  • 376,765
  • 198
  • 813
  • 562
Dan
  • 651
  • 2
  • 8
  • 19

5 Answers5

12

Simply access the tick labels and change them:

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

enter image description here

CT Zhu
  • 52,648
  • 17
  • 120
  • 133
9

The objects in the date_range DF are Timestamp objects. Call Timestamp.strftime on 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 for more general formatting options versus truncating the ticklabel string.

wflynny
  • 18,065
  • 5
  • 46
  • 67
  • Thanks! Accepted yours because it let me call strftime and thus allows for more formatting options, as you pointed out – Dan Apr 15 '14 at 16:03
8

You could just pass new labels exactly with your preferred strftime:

ax.set_xticklabels([pandas_datetime.strftime("%Y-%m-%d") for pandas_datetime in df.index])

It's not the prettiest answer, but it gets the job done consistently.

RCCG
  • 175
  • 2
  • 7
3

The easiest solution for me was:

from matplotlib.dates import DateFormatter

date_form = DateFormatter("%Y-%m-%d")
ax.xaxis.set_major_formatter(date_form)
Daniello
  • 175
  • 14
0

This gets the job done but it is not ideal. RCCG's answer is perfect bc it does not change the datetime type of the index.

df.index=df.index.date
df.plot(kind='bar)
Lei Z
  • 11
  • 1