AnneS
AnneS

Reputation: 1583

How to set dates in x axis with non-uniform interval?

I would like to draw a time-plot using the matplotlib.dates module. From the tutorial, I know how to set regular interval date like the following:

ax.xaxis.set_major_locator(DayLocator())
ax.xaxis.set_major_formatter(DateFormatter("%Y-%m"))
ax.xaxis.set_minor_...

However, in my data there are some months missing. My xaxis date is more like : Jan, Feb, May, Jul, Sep, Oct, Sep... no pattern is formed...

How can I deal with such situation?.

Upvotes: 2

Views: 4453

Answers (2)

Mauro
Mauro

Reputation: 1241

If I understand correctly you may need to use

matplotlib.ticker.FixedLocator

Example which puts labels at data points 1, 10 and the last one:

import pylab as plt
from matplotlib.ticker import FixedLocator
from matplotlib.dates import DateFormatter
import numpy as np
from datetime import datetime

# dates (unequally spaced, but works exactly same for equally spaced dates too)
dates = plt.date2num(datetime(2010,3,1))  + np.array([0, 10, 50, 100, 180, 300])
# just some data
data = dates**2
plt.plot_date(dates,data)

ax = plt.gca()
ax.xaxis.set_major_locator(FixedLocator(dates[[1, 3, len(dates)-1]]))
# for some reason this is needed to get the month displayed too
ax.xaxis.set_major_formatter(DateFormatter("%Y-%m"))
plt.show()

Upvotes: 2

yosukesabai
yosukesabai

Reputation: 6244

Starting from Mauro's solution, i tried to plot data pair where dates are irregularly spaced, so that i can find this QA sometime in future.

import pylab as plt
from matplotlib.ticker import FixedLocator
from matplotlib.dates import DateFormatter
import numpy as np
from datetime import datetime

# dates, irregularly spaced
y = 2010, 2010, 2010, 2011, 2011
m =    9,   11,   12,    3,    4


dates = np.array([plt.date2num(datetime(yy,mm,1)) for yy,mm in zip(y,m)])
print dates


# just some data
data = dates**2
print data


plt.plot_date(dates,data)

ax = plt.gca()
# need some more thnking for properly locate which date to label
#ax.xaxis.set_major_locator(FixedLocator(dates[[1, 10, len(dates)-1]]))
ax.xaxis.set_major_formatter(DateFormatter("%Y-%m"))
plt.show()

enter image description here

Upvotes: 0

Related Questions