Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to plot a horizontal line in matplotlib

Understanding the Basics of Plotting with Matplotlib

Before we dive into plotting a horizontal line, let's first get a basic understanding of what Matplotlib is. Matplotlib is a popular Python library used for creating a wide variety of static, animated, and interactive visualizations. Think of it like a digital artist's toolkit that allows you to paint a picture with data.

Starting with a Simple Plot

To begin, let's create a simple plot. This will be our canvas before we draw our horizontal line. Here's how you can create a basic plot:

import matplotlib.pyplot as plt

# Sample data
x = [0, 1, 2, 3, 4]
y = [0, 1, 4, 9, 16]

# Creating a figure and a set of subplots
fig, ax = plt.subplots()

# Plot the data
ax.plot(x, y)

# Show the plot

When you run this code, a window will pop up showing a graph of the data points you've entered. The plt.subplots() function creates a figure and a set of subplots, which you can think of as a blank piece of paper (figure) and a space to draw (subplot). The ax.plot() function then takes your x and y data and draws a line through the points on your subplot.

Introducing the Horizontal Line

Now, let's add a horizontal line to our plot. In the world of graphs, a horizontal line runs from left to right and has a constant y-value. Imagine it as the horizon you see when you look out at the sea; it's flat and stretches across your field of vision.

Plotting a Horizontal Line with axhline

Matplotlib makes it easy to add such a line with the axhline function. The axhline stands for 'axis horizontal line'. Here's how you can use it to add a horizontal line at y=3:

# ... (previous code)

# Adding a horizontal line at y=3
ax.axhline(y=3, color='r', linewidth=2)

# Show the plot with the horizontal line

The y parameter specifies the height of the line on the y-axis, color sets the color of the line (in this case, 'r' for red), and linewidth determines how thick the line will be.

Customizing the Horizontal Line

Matplotlib allows you to customize your horizontal line in various ways. You can change its color, style, and even make it dashed or dotted. Here's an example of a dashed horizontal line with a blue color:

# ... (previous code)

# Adding a customized horizontal line at y=2
ax.axhline(y=2, color='b', linewidth=2, linestyle='--')

# Show the plot with the customized horizontal line

The linestyle parameter lets you choose the style of the line. The '--' value makes the line dashed.

Understanding Axes and Limits

Sometimes, you might want your horizontal line to span a specific range on the x-axis. To do this, you need to understand the concept of axes and limits. The axes are the lines that border the graph area, and limits are the minimum and maximum values that the axes can display.

Creating a Horizontal Line with Limited Range

To create a horizontal line that spans from x=1 to x=3, you can use the hlines function. Here's how:

# ... (previous code)

# Adding a horizontal line from x=1 to x=3 at y=1.5
ax.hlines(y=1.5, xmin=1, xmax=3, color='g', linewidth=2)

# Show the plot with the range-limited horizontal line

In this example, xmin and xmax define the start and end points of the line on the x-axis, and y defines the constant y-value. The line is green ('g') and has a thickness of 2.

Using Horizontal Lines to Highlight Thresholds

Horizontal lines are often used to highlight specific thresholds or important values. For instance, if you're visualizing test scores, you might want to draw a line at the passing grade level.

# ... (previous code)

# Adding a threshold line for a passing score
passing_score = 70
ax.axhline(y=passing_score, color='orange', linewidth=2, linestyle=':')

# Show the plot with the threshold line

In this example, the y parameter is set to the passing score value, and the linestyle is set to ':', which creates a dotted line.

Combining Multiple Plots and Lines

Matplotlib allows you to combine multiple lines and plots in a single figure. This is useful when you want to compare data or add multiple reference lines.

# ... (previous code)

# Adding another dataset
y2 = [1, 2, 3, 4, 5]
ax.plot(x, y2, label='Dataset 2')

# Adding multiple horizontal lines
ax.axhline(y=2.5, color='purple', linewidth=1, linestyle='-.')
ax.axhline(y=4.5, color='brown', linewidth=1, linestyle='-')

# Adding a legend to distinguish datasets and lines

# Show the combined plot

In this code, a second dataset is plotted, and two additional horizontal lines are added with different styles. The ax.legend() function creates a legend that helps distinguish between the different datasets and lines.


Adding horizontal lines to your plots in Matplotlib is a simple yet powerful way to enhance the readability and interpretability of your visualizations. Whether you're marking thresholds, emphasizing averages, or simply guiding the viewer's eye, horizontal lines serve as a useful tool in your plotting arsenal.

As you continue your journey in programming and data visualization, remember that these tools are like colors on a palette—use them wisely to convey meaning and tell the story behind your data. Have fun experimenting with different styles and customizations, and you'll soon be creating informative and visually appealing plots that can speak volumes.