How to plot vertical lines in Pandas and matplotlib?

In this Data Visualization tutorial, we will learn how to draw one or multiple vertical lines using matplotlib and Pandas.

Drawing vertical lines in Pandas and Matplotlib

The plt.axvline() method allows to easily add vertical lines to plots we rended using matplotlib, pandas and Seaborn. Here’s a simple example:

fig, ax = plt.subplots()
ax.axvline(x = <x_position>, color = <line_color>, linestyle= <line_style);

Step #1: Import Data Analysis libraries

We’ll start by importing libraries, numpy will be used to generate some random data for the example.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

Step #2: Create data for our plots

We’ll create a couple of ndarrays and then initialize a DataFrame from the Numpy arrays.

x = np.linspace(50,100,num = 50)
y = x * np.random.random(50)
sales_dict = dict(x=x, y=y)
sales = pd.DataFrame(sales_dict)

Step #3: Plot a chart with vertical line with Pandas

We can now easily draw our plot. Note that we’ll using the axvline method to render the vertical line. We use the linestyle parameter to style the rendered line. We then added a labeled text to better explain the chart.

scatter_plot = sales.plot(x='x', y='y', kind='scatter')
scatter_plot.set_title('Productivity by Team')

scatter_plot.axvline(x = 85, color = 'green', linestyle='-.');
# add a label to vertical line
scatter_plot.text(x=70, y=0, s= 'Productivity target', color= 'green');

Here’s our chart:

Step #4: Draw multiple vertical lines on a matplotlib chart

In our last example we will draw multiple vertical lines into our figure:

fig, ax = plt.subplots()
ax.set_title('Productivity by Team')
ax.axvline(x = 85, color = 'green', linestyle='-');
ax.axvline(x = 90, color = 'black', linestyle=':');
ax.text(x=70, y=0, s= 'Meeting target', color= 'green');
ax.text(x=88, y=0, s= 'Exceeding target', color= 'black');

Here’s the chart, note the multiple lines we drew, each with it’s own style.

Follow up learning

How to plot multiple lines in a matplotlib chart?