在matplotlib中为日期格式的时间序列添加垂直线 [英] Adding vertical line to Date formatted time-series in matplotlib

查看:343
本文介绍了在matplotlib中为日期格式的时间序列添加垂直线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

或:

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) 

这里是函数,它很好地起作用:

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


推荐答案

您必须给 axvline 方法是一个数字值,而不是字符串。您可以通过定义一个将日期的字符串表示形式转换为 datenums 的转换器来实现。您的 np.loadtxt 方法调用中已经有一个这样的转换器。如果将其定义为函数,则可以在加载数据时使用它,也可以将其用于单个日期字符串。

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

这篇关于在matplotlib中为日期格式的时间序列添加垂直线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆