如何用非均匀间隔在x轴上设置日期?

时间:2011-11-02 19:44:22

标签: python matplotlib

我想使用matplotlib.dates模块绘制时间图。从教程中,我知道如何设置如下的常规间隔日期:

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

然而,在我的数据中,有几个月没有了。我的xaxis日期更像是:Jan,Feb,May,Jul,Sep,Oct,Sep ...没有形成模式......

我该如何处理这种情况?

2 个答案:

答案 0 :(得分:2)

如果我理解正确,您可能需要使用

matplotlib.ticker.FixedLocator

将标签放在数据点1,10和最后一个的示例:

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()

答案 1 :(得分:0)

从Mauro的解决方案开始,我试图绘制日期不规则间隔的数据对,以便我可以在将来的某个时间找到此QA。

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