1

I'm having trouble deciphering the documentation for changing tick frequency and date formatting with pandas.

For example:

import numpy as np
import pandas as pd
import pandas.io.data as web
import matplotlib as mpl
%matplotlib inline

mpl.style.use('ggplot')
mpl.rcParams['figure.figsize'] = (8,6)

# grab some price data
px = web.DataReader('AAPL', "yahoo", '2010-12-01')['Adj Close']
px_m = px.asfreq('M', method='ffill')
rets_m = px_m.pct_change()

rets_m.plot(kind='bar')

generates this plot:

Generated plot

Yikes. How can I get the ticks to be every month or quarter or something sensible? And how can the date formatting be changed to get rid of times?

I've tried various things with ax.set_xticks() and ax.xaxis.set_major_formatter but haven't been able to figure it out.

Serenity
  • 35,289
  • 20
  • 120
  • 115
itzy
  • 11,275
  • 15
  • 63
  • 96
  • 1
    Possible duplicate of [Pandas timeseries plot setting x-axis major and minor ticks and labels](http://stackoverflow.com/questions/12945971/pandas-timeseries-plot-setting-x-axis-major-and-minor-ticks-and-labels) – Fabio Lamanna Dec 10 '15 at 16:58

1 Answers1

2

If you use the plot method in pandas, the set_major_locator and set_major_formatter methods of matplotlib is likely to fail. It might just be easier to manually adjust the ticks, if you want to stay with pandas``plot methods.

#True if it is the first month of a quarter, False otherwise
xtick_idx = np.hstack((True, 
                       np.diff(rets_m.index.quarter)!=0))

#Year-Quarter string for the tick labels.
xtick     = ['{0:d} quarter {1:d}'.format(*item) 
             for item in zip(rets_m.index.year, rets_m.index.quarter)]
ax        =rets_m.plot(kind='bar')

#Only put ticks on the 1st months of each quarter
ax.xaxis.set_ticks(np.arange(len(xtick))[xtick_idx])

#Adjust the ticklabels
ax.xaxis.set_ticklabels(np.array(xtick)[xtick_idx])

enter image description here

Community
  • 1
  • 1
CT Zhu
  • 52,648
  • 17
  • 120
  • 133
  • 1
    Thanks! Derived from this answer, I wrote the [following example](https://gist.github.com/drorata/5165c7ac935a6162714043300852d2b6). – Dror Sep 19 '17 at 08:53
  • @Dror You should add this as a proper answer, since it contains additional information. – Serge Stroobandt Oct 02 '17 at 16:51