'How to add overlaying lines in matplotlib at specific points

I've created a simple line graph:

x = df['dates']
y = df['score']
plt.plot(x, y, marker = 'o')
plt.show()

enter image description here

I have a second dateframe(df2) with a couple dates of interest

df2['dates_of_interest']

2021-07-15
2021-09-30

How can I overlay those two dates with two lines on the graph I've already created so it would look something like this:

enter image description here



Solution 1:[1]

You can use plt.axvline function to add a vertical line.

import matplotlib.pyplot as plt
import pandas as pd
from datetime import datetime

df = pd.DataFrame({'dates':[datetime(2021,m,1) for m in range(2, 13)],
                   'score':range(2, 13)})

plt.plot(df['dates'], df['score'], marker='o')
plt.xticks(rotation=45)


plt.axvline(datetime(2021,7,15), ls='--')
plt.axvline(datetime(2021,9,30), ls='--')

plt.show()

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Z-Y.L