在具有相同日期时间轴的子图中添加垂直线

Add vertical line across subplots that have the same datetime axis

我一直在尝试在具有相同 DateTime x 轴的子图中添加一条垂直线。我使用的代码是:

import datetime as dt
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import pickle

# Import data for minimum reproducible example #
file_to_read = open("example.dat", "rb")

B = pickle.load(file_to_read)

file_to_read.close()

## I would like to use something like this to locate the 
## point that correspond to that datetime and plot the vertical line
dt2 = pd.to_datetime("2018-10-31 06:43:10.000000")
dt3  = pd.to_datetime("2018-10-31 06:43:35.600000")

s2  = B.index.unique().get_loc(dt2, method='nearest')
s2a  = B.index.unique().get_loc(dt3, method='nearest')


size=21
int1=1
fig, axs = plt.subplots(2, sharex=True)

axs[1].plot(B.L,linewidth=3,label='$B_{z}$')
axs[1].plot(B.M,linewidth=3,label='$B_{y}$')
axs[1].plot(B.N,linewidth=3,label='$B_{x}$')
axs[1].tick_params(axis='both',labelsize=size-3)
axs[1].legend( fontsize=size)
axs[1].legend(frameon=False, loc='upper left', ncol=3, fontsize=size)
axs[1].set_ylim([-80,50])
axs[1].set_ylabel(r'$B_{NML} \ (nT)$', fontsize=size)


axs[0].plot(B.Total,linewidth=3,color='black',label='$|B|$')
axs[0].legend(loc=4, fontsize=size)
axs[0].legend(frameon=False, loc='lower left', ncol=1, fontsize=size)
axs[0].tick_params(axis='both',labelsize=size-3)
axs[0].set_ylim([0,90])
axs[0].set_ylabel(r'$B_{tot} \ (nT)$', fontsize=size)

## axis limits ##
axs[0].set_xlim([dt2, dt3])

## Add title ##
fig.text(0.5, 0.9, '2018 Oct 31', ha='center', va='center',fontsize=size)

## Gap between subplots
plt.subplots_adjust(wspace=0.01, hspace=0.12)

## add vertical line ##
line = plt.Line2D((.42,.42),(.125,.88),color='b',linewidth=1)
line2 = plt.Line2D((.55,.55),(.125,.88),color='b',linewidth=1)
fig.add_artist(line)
fig.add_artist(line2)


plt.plot()

我可以添加一条垂直线,但我想使该过程自动化。例如插入 DateTime 并绘制它,而不是猜测图中与该日期时间对应的点。例如使用这样的东西:

dt2 = pd.to_datetime("2018-10-31 06:43:10.000000")
dt3  = pd.to_datetime("2018-10-31 06:43:35.600000")

s2  = B.index.unique().get_loc(dt2, method='nearest')
s2a  = B.index.unique().get_loc(dt3, method='nearest')

可在此处找到最小可重现示例所需的数据:https://www.dropbox.com/s/w9gblp3dc361nw6/example.dat?dl=0

就像@MrFuppes 说的,如果你不关心两个子图之间没有一条线,axvline 应该足够了:

dt5 = B.index[5]
dt10 = B.index[10]
    
axs[0].axvline(dt5, color='r', ls='dashed')
axs[1].axvline(dt5, color='r', ls='dashed')
    
axs[0].axvline(dt10, color='k', ls='dashed')
axs[1].axvline(dt10, color='k', ls='dashed')