matplotlib提供基本的接口:
from matplotlib.dates import AutoDateLocator, DateFormatter
autodates = AutoDateLocator()
yearsFmt = DateFormatter('%Y-%m-%d %H:%M:%S')
figure.autofmt_xdate() #设置x轴时间外观
ax.xaxis.set_major_locator(autodates) #设置时间间隔
ax.xaxis.set_major_formatter(yearsFmt) #设置时间显示格式
ax.set_xticks() #设置x轴间隔
ax.set_xlim() #设置x轴范围
在matplotlib里面x轴时间对应一个浮点数。一个单位的浮点数表示一天。
浮点数和时间之间的转换接口:
import matplotlib.dates as dt
dt提供的三个接口
num2date(x, tz=None)
*x* is a float value which gives the number of days
(fraction part represents hours, minutes, seconds) since
0001-01-01 00:00:00 UTC *plus* *one*.
The addition of one here is a historical artifact. Also, note
that the Gregorian calendar is assumed; this is not universal
practice. For details, see the module docstring.
Return value is a :class:`datetime` instance in timezone *tz* (default to
rcparams TZ value).
If *x* is a sequence, a sequence of :class:`datetime` objects will
be returned.
date2num(d)
*d* is either a :class:`datetime` instance or a sequence of datetimes.
Return value is a floating point number (or sequence of floats)
which gives the number of days (fraction part represents hours,
minutes, seconds) since 0001-01-01 00:00:00 UTC, *plus* *one*.
The addition of one here is a historical artifact. Also, note
that the Gregorian calendar is assumed; this is not universal
practice. For details, see the module docstring.
num2date(x, tz=None)
*x* is a float value which gives the number of days
(fraction part represents hours, minutes, seconds) since
0001-01-01 00:00:00 UTC *plus* *one*.
The addition of one here is a historical artifact. Also, note
that the Gregorian calendar is assumed; this is not universal
practice. For details, see the module docstring.
Return value is a :class:`datetime` instance in timezone *tz* (default to
rcparams TZ value).
If *x* is a sequence, a sequence of :class:`datetime` objects will
be returned.
时间和浮点数的转换最好使用matplotlib.dates里面的接口。调用python datetime里面的接口生成的浮点数会比较大。matplotlib识别不了,抛出异常。
由于set_xticks和set_xlim的参数都是整数。所以x轴最小间隔是一天。