Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 216
Dan Avatar asked Apr 15 '14 15:04

Dan


People also ask

How do I change the date format in MatPlotLib?

Using the DateFormatter module from matplotlib, you can specify the format that you want to use for the date using the syntax: "%X %X" where each %X element represents a part of the date as follows: %Y - 4 digit year with upper case Y. %y - 2 digit year with lower case y. %m - month as a number with lower case m.

How do I change date format to MM DD YYYY in pandas?

Please notice that you can also specify the output date format other than the default one, by using the dt. strftime() method. For example, you can choose to display the output date as MM/DD/YYYY by specifying dt. strftime('%m/%d/%Y') .

How do I format a date axis in MatPlotLib?

MatPlotLib with Python Create a figure and a set of subplots using subplots() method. Plot the dataframe using plot method, with df's (Step 1) time and speed. To edit the date formatting from %d-%m-%d to %d:%m%d, we can use set_major_formatter() method. Set the formatter of the major ticker.


4 Answers

The easiest solution for me was:

from matplotlib.dates import DateFormatter

date_form = DateFormatter("%Y-%m-%d")
ax.xaxis.set_major_formatter(date_form)
like image 182
Daniello Avatar answered Sep 22 '22 09:09

Daniello


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.

like image 27
wflynny Avatar answered Oct 16 '22 17:10

wflynny


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

like image 13
CT Zhu Avatar answered Oct 16 '22 16:10

CT Zhu


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.

like image 7
RCCG Avatar answered Oct 16 '22 16:10

RCCG