What kind of set_major_locator should I use?

15.1k views Asked by At

I have a question regarding a plot feature when the X-Axis is a date.

Setting

I have a two time-series dt and x, where dt is a list of datetime.datetime values and x is a numpy array object.

dt = 
[datetime.datetime(1996, 12, 3, 0, 0), 
 datetime.datetime(1996, 12, 4, 0, 0), 
 ...,
 datetime.datetime(2015, 6, 5, 0, 0), 
 datetime.datetime(2015, 6, 8, 0, 0)]

x = 
array([29.06262, 29.26933, ..., 208.41999, 208.44532])

and both have the same length.

When I plot them as :

ax.plot(dt, x, color='black', lw=2)

I get a chart which has X-Tick Labels as their years (e.g. 1994, 1998, 2002, 2006, 2010, 2014).

After some zooming, the X-Tick Labels nicely start showing months (e.g. Aug 2009, Oct 2009, Dec 2009, Feb 2010, Apr 2010, Jun 2010).

After further zooming, the X-Tick Labels again nicely start showing days (e.g. Jan 14 2010, Jan 21 2010, Jan 28 2010, Feb 04 2010, Feb 11 2010, Feb 18 2010).

Question

Now, I am trying to draw a custom chart (e.g. say using LineCollection) instead of using the default plot.

I suspect I would need to use ax.xaxis.set_major_locator(???) and ax.xaxis.set_major_formatter(???) to get the same feature of the X-Axis as in the default plot function.

What do I need to provide (i.e. ???) to ax.xaxis.set_major_locator(???) and ax.xaxis.set_major_formatter(???) ?

1

There are 1 answers

1
hitzg On BEST ANSWER

Yes, you assumption was right: You have to set the locator and formatter manually. The "regular" ones are available in matplotlib.ticker and the ones related to dates in matplotlib.dates. There is quite a variety of fixed ones (e.g. WeekdayLocator, MicrosecondLocator, etc.), but also the automatic ones that you get when using plot.

So this should do it:

import matplotlib.pyplot as plt
import matplotlib.dates as mdates

# all your fancy plotting code

ax.xaxis.set_major_locator(mdates.AutoDateLocator())
ax.xaxis.set_major_formatter(mdates.AutoDateFormatter())

plt.show()

Further reading: http://matplotlib.org/api/dates_api.html

Extra:

Be careful with you list of datetimes: matplotlib has an internal date/time representation (number of days as floats) and thus datetime objects need to be converted before plotting. In plot this conversion happens automatically, for custom graphs you might have to do that yourself with matplotlib.dates.date2num.