How to plot an horizontal line in Pandas charts?

In this short tutorial we will learn how to use Python and the Pandas library to draw an horizontal line that runs in parallel to the x axes.

Create Example Data

As we typically do, we will start by importing the necessary Data Analysis libraries and create some example data that we will use.

# numpy is optional here and required to create the test data
import pandas as pd
import numpy as np

# define x and y values for the chart
x = np.linspace(0,10, num=10)
y = x * np.random.randint(0,3,size=10)

# create a Pandas DataFrame
my_dict = dict(x=x, y=y)
data = pd.DataFrame (my_dict) 

Create a Pandas chart with horizontal line

With after creating the data, we can go ahead and render the chart. In this example we chose to draw a bar plot, but this recipe is completely relevant for scatters, line plots, boxplot, histograms and any other chart. Note that in order to draw the graph, we haven’t imported the matplotlib library, as the required functionality is available as part of the pandas library.

# initialize a bar chart
bar_plot = data.plot(kind='bar', \
                     title = 'Bar chart with horizontal line');
# define the legend location
bar_plot.legend(loc='upper left');
# define a grid
bar_plot.grid();

Let’s take a look:

Now we can go ahead and draw the horizontal line using the axhline method. The syntax is pretty self explanatory:

bar_plot = data.plot(kind='bar', title = 'Bar chart with horizontal line');
bar_plot.legend(loc='upper left');
bar_plot.grid(axis='y');
#draw the line
bar_plot.axhline(y=9, color= 'green', linewidth=2,)
# add text
bar_plot.text(x= 0, y=9.25, s='target');

Here is our new chart:

Draw a vertical line

For completeness, here’s a short recipe that allow to draw a vertical line on your Pandas chart using the axvline() method.

bar_plot = data.plot(kind='bar', title = 'Bar chart with vertical line');
bar_plot.axvline (x= 4.5, color = 'green');

Follow up learning