Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding vertical line to Date formatted time-series in matplotlib

I am trying to add a red vertical line to a plot of a timeseries where the x-axis is formatted as %Y-%m-%d. The date at which I would like to add the line is 2013-05-14. Simply adding the line before "plt.show()":

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

or:

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

returns the error:

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) 

Here is the function, which works well as it is:

 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()
like image 418
shbrainard Avatar asked Mar 23 '23 03:03

shbrainard


1 Answers

You have to give the axvline method a numerical value, not a string. You can achieve this by defining a converter that converts sting representations of dates to datenums. You already have one such converter in your np.loadtxt method call. If you define it as a function, you can use it both when loading the data, and for single date strings.

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

like image 69
sodd Avatar answered Apr 18 '23 12:04

sodd