【问题标题】:Adding vertical line to Date formatted time-series in matplotlib在 matplotlib 中向日期格式的时间序列添加垂直线
【发布时间】:2013-07-17 14:13:19
【问题描述】:

我正在尝试在 x 轴格式为 %Y-%m-%d 的时间序列图中添加一条红色垂直线。我想添加该行的日期是 2013-05-14。只需在“plt.show()”之前添加一行:

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

【问题讨论】:

    标签: matplotlib time-series date-formatting


    【解决方案1】:

    你必须给axvline 方法一个数值,而不是一个字符串。您可以通过定义一个将日期的字符串表示形式转换为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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-13
      • 2017-07-13
      • 1970-01-01
      • 2020-04-26
      • 1970-01-01
      • 2020-05-15
      • 2022-12-13
      • 1970-01-01
      相关资源
      最近更新 更多