2013-07-18 44 views
3

我正在嘗試將時間序列的x軸被格式化爲%y-%m-%d的時間序列圖中添加一條紅色垂直線。我想添加該行的日期是2013-05-14。簡單地增加前行 「plt.show()」:在matplotlib中向日期格式化的時間序列添加垂直線

plt.axvline(x=2013-05-14) 

或:

plt.axvline(x='2013-05-14') 

返回錯誤:

RuntimeError: RRuleLocator estimated to generate 23972 ticks from 0044-05-12 23:59:59.999990+00:00 to 2013-06-07 00:00:00.000010+00:00: exceeds Locator.MAXTICKS * 2 (2000) 

下面是函數,因爲它效果很好是:

def time_series(self): 
    fig = plt.figure(figsize=(20, 20), frameon = False) 
    ax1 = fig.add_subplot(3, 1, 1) 


    d_dates, d_flux_n2o, d_sem_n2o = np.loadtxt('%stime_series/dynamic.csv' %self.dir['r_directory'], delimiter = ',', unpack=True, converters={0: mdates.strpdate2num('%Y-%m-%d')}) 

    ax1.set_xlabel('Date') 
    ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d')) 
    ax1.xaxis.set_major_locator(mdates.MonthLocator()) 
    ax1.xaxis.set_minor_locator(mdates.DayLocator()) 
    plt.gcf().autofmt_xdate() 

    ax1.errorbar(d_dates, d_flux_n2o, yerr=d_sem_n2o, fmt="y-", linewidth=1.5, label = 'Biodynamic') 
    ax1.legend(loc = 0) 

    plt.show() 

回答

6

您必須給axvline方法是一個數值,而不是一個字符串。您可以通過定義一個轉換器來將日期的sting表示轉換爲datenums。您的np.loadtxt方法調用中已經有一個這樣的轉換器。如果將其定義爲函數,則可以在加載數據時和單個日期字符串中使用它。

import matplotlib.dates as mdates 
import matplotlib.pyplot as plt 
import numpy as np 


def time_series(self): 
    fig = plt.figure(figsize=(20, 20), frameon = False) 
    ax1 = fig.add_subplot(3, 1, 1) 

    # Converter to convert date strings to datetime objects 
    conv = np.vectorize(mdates.strpdate2num('%Y-%m-%d')) 


    d_dates, d_flux_n2o, d_sem_n2o = np.loadtxt('%stime_series/dynamic.csv' %self.dir['r_directory'], delimiter = ',', unpack=True, converters={0: conv}) 

    ax1.errorbar(d_dates, d_flux_n2o, yerr=d_sem_n2o, fmt="y-", linewidth=1.5, label = 'Biodynamic') 
    ax1.legend(loc = 0) 
    ax1.axvline(conv('2013-05-14'), color='r', zorder=0) 

    ax1.set_xlabel('Date') 
    ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d')) 
    ax1.xaxis.set_major_locator(mdates.MonthLocator()) 
    ax1.xaxis.set_minor_locator(mdates.DayLocator()) 
    plt.gcf().autofmt_xdate() 

    plt.show() 

enter image description here