tags
tags

Reputation: 4059

Mofifying X-axis unit on Python graphs

The following lines:

import Quandl
import datetime
import matplotlib.pyplot as plt

# Import data from Quandl
DJI  = Quandl.get("WREN/W6", trim_start="1980-01-01", trim_end= datetime.date.today())

'''
type(DJI)   =>   class 'pandas.core.frame.DataFrame'
'''

# Plot DJI
DJI.plot()
plt.show()

Produce this chart:

enter image description here

How can I set the major unit so that each year from the start to the end of my series reads and read only once?

Maybe using MultipleLocator and FormatStrFormatter functions? But how does that work with dates ? The length of my time series my vary.

Upvotes: 0

Views: 344

Answers (2)

Phillip Cloud
Phillip Cloud

Reputation: 25662

You'll need to actually call plt.plot (or use the matplotlib API) since matplotlib doesn't correctly render datetime64 arrays on the x-axis. For example:

In [18]: s = Series(randn(10), index=date_range('1/1/2001', '1/1/2011', freq='A'))

In [19]: s
Out[19]:
2001-12-31   -1.236
2002-12-31    0.234
2003-12-31   -0.858
2004-12-31   -0.472
2005-12-31    1.186
2006-12-31    1.476
2007-12-31    0.212
2008-12-31    0.854
2009-12-31   -0.697
2010-12-31   -1.241
Freq: A-DEC, dtype: float64

In [22]: ax = s.plot()

In [23]: ax.xaxis.set_major_locator(YearLocator())

In [24]: ax.xaxis.set_major_formatter(DateFormatter('%Y'))

gives

enter image description here

Instead you should do something like:

fig, ax = subplots()
ax.plot(s.index.to_pydatetime(), s.values)
ax.xaxis.set_major_locator(YearLocator())
ax.xaxis.set_major_formatter(DateFormatter('%Y'))
fig.autofmt_xdate()

to get:

enter image description here

If you want different year multiples, pass the multiple you want to the YearLocator constructor, like so:

fig, ax = subplots()
ax.plot(s.index.to_pydatetime(), s.values)
ax.xaxis.set_major_locator(YearLocator(2))
ax.xaxis.set_major_formatter(DateFormatter('%Y'))
fig.autofmt_xdate()

resulting in:

enter image description here

Upvotes: 2

sodd
sodd

Reputation: 12923

You can use YearLocator from matplotlib's dates module.

from matplotlib.dates import YearLocator, DateFormatter

...

# YearLocator defaults to a locator at 1st of January every year
plt.gca().xaxis.set_major_locator(YearLocator())

plt.gca().xaxis.set_major_formatter(DateFormatter('%Y'))

Upvotes: 2

Related Questions