How to Add Vertical Line at Specific Date in Matplotlib


You can use the axvline() function to along with the datetime() function to add a vertical line at a specific date in Matplotlib:

import datetime
import matplotlib.pyplot as plt

plt.axvline(datetime.datetime(2023, 1, 5))

This particular example adds a vertical line at 1/5/2023 on the x-axis of a plot in Matplotlib.

The following example shows how to use this syntax in practice.

Example: Add Vertical Line at Specific Date in Matplotlib

Suppose we have the following pandas DataFrame that contains information about the total sales made on eight consecutive days at some company:

import datetime
import numpy as np
import pandas as pd

#create DataFrame
df = pd.DataFrame({'date': np.array([datetime.datetime(2020, 1, i+1)
                                     for i in range(8)]),
                   'sales': [3, 4, 4, 7, 8, 9, 14, 17]})

#view DataFrame
print(df)

        date  sales
0 2023-01-01      3
1 2023-01-02      4
2 2023-01-03      4
3 2023-01-04      7
4 2023-01-05      8
5 2023-01-06      9
6 2023-01-07     14
7 2023-01-08     17

We can use the following code to create a plot of sales by day and add a vertical line at the date 1/5/2023 on the x-axis:

import matplotlib.pyplot as plt

#plot sales by date
plt.plot_date(df.date, df.sales)

#rotate x-axis ticks 45 degrees and right-aline
plt.xticks(rotation=45, ha='right')

#add vertical line at 1/5/2023
plt.axvline(datetime.datetime(2023, 1, 5))

Matplotlib add vertical line at specific date

Notice that a vertical line has been added to the plot at the date 1/5/2023 on the x-axis.

Also note that you can use the color, linewidth, and linestyle arguments to customize the appearance of the line:

import matplotlib.pyplot as plt

#plot sales by date
plt.plot_date(df.date, df.sales)

#rotate x-axis ticks 45 degrees and right-aline
plt.xticks(rotation=45, ha='right')

#add customized vertical line at 1/5/2023
plt.axvline(datetime.datetime(2023, 1, 5), color='red', linewidth=3, linestyle='--')

Notice that the vertical line is now red, slightly wider than the previous example, and dashed.

Feel free to modify the appearance of the vertical line to make it look however you’d like.

Additional Resources

The following tutorials explain how to perform other common tasks in Matplotlib:

How to Add an Average Line to Plot in Matplotlib
How to Add a Trendline in Matplotlib
How to Draw a Horizontal Line in Matplotlib

Leave a Reply

Your email address will not be published. Required fields are marked *