1. 程式人生 > >matplotlib x軸時間顯示

matplotlib x軸時間顯示

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軸最小間隔是一天。