python
  • numpy
  • matplotlib
  • 2014-02-26 67 views 4 likes 
    4

    我有此Python代碼爲隨着時間的推移顯示一些數字:如何在matplotlib.pyplot中繪圖時顯示日期?

    import matplotlib.pyplot as plt 
    import datetime 
    import numpy as np 
    
    x = np.array([datetime.datetime(2013, 9, i).strftime("%Y-%m-%d") for i in range(1,5)], 
          dtype='datetime64') 
    y = np.array([1,-1,7,-3]) 
    plt.plot(x,y) 
    plt.axhline(linewidth=4, color='r') 
    plt.show() 
    

    所得圖形具有數目0.0至3.0,在x軸:

    enter image description here

    什麼是最簡單的方法顯示日期而不是這些數字?最好以格式%b%d。

    回答

    4

    According to efiring,matplotlib不支持NumPy datetime64對象(至少現在還沒有)。因此,轉換x Python的datetime.datetime對象:

    x = x.astype(DT.datetime) 
    

    接下來,您可以指定x軸的刻度格式是這樣的:

    xfmt = mdates.DateFormatter('%b %d') 
    ax.xaxis.set_major_formatter(xfmt) 
    

    import matplotlib.pyplot as plt 
    import matplotlib.dates as mdates 
    import datetime as DT 
    import numpy as np 
    
    x = np.array([DT.datetime(2013, 9, i).strftime("%Y-%m-%d") for i in range(1,5)], 
          dtype='datetime64') 
    x = x.astype(DT.datetime) 
    y = np.array([1,-1,7,-3]) 
    fig, ax = plt.subplots() 
    ax.plot(x, y) 
    ax.axhline(linewidth=4, color='r') 
    xfmt = mdates.DateFormatter('%b %d') 
    ax.xaxis.set_major_formatter(xfmt) 
    plt.show() 
    

    enter image description here

    +0

    其實我只使用NumPy datetime64對象,因爲我認爲它會幫助,所以只是x = np.array([datetime .datetime(2013,9,i)for i in range(1,5)])。 – vfxGer

    相關問題