Skip to content Skip to sidebar Skip to footer

Matplotlib With Dates - Changing Labels And Ticks For Monthly Data

I have a dataframe like this: data_ = list(range(106)) index_ = pd.period_range('3/1/2004', '12/1/2012', freq='M') df2_ = pd.DataFrame(data = data_, index = index_, columns = ['da

Solution 1:

With regards to constructing the timedelta, datetime.timdelta() doesn’t have a parameter to specify months, so it’s probably convenient to stick to pd.date_range(). However, I found that objects of type pandas.tslib.Timestamp don’t play nice with matplotlib ticks so you could convert them to datetime.date objects like so

index_ = [pd.to_datetime(date, format='%Y-%m-%d').date() 
        fordatein pd.date_range('2004-03-01', '2012-12-01', freq="M")]

It’s possible to add gridlines and customise axes labels by first defining a matplotlib axes object, and then passing this to DataFrame.plot()

ax = plt.axes()
df2_.plot(ax=ax)

Now you can add vertical gridlines to your plot

ax.xaxis.grid(True)

And specify quarterly xticks labels by using matplotlib.dates.MonthLocator and setting the interval to 3

ax.xaxis.set_major_locator(dates.MonthLocator(interval=3))

And finally, I found the ticks to be to be very crowded so I formatted them to get a nicer fit

ax.xaxis.set_major_formatter(dates.DateFormatter('%b %y'))
labels = ax.get_xticklabels()
plt.setp(labels, rotation=85, fontsize=8)

To produce the following:

enter image description here

Post a Comment for "Matplotlib With Dates - Changing Labels And Ticks For Monthly Data"