How to Draw Horizontal Lines in Matplotlib

When I was working with data visualization in Python, plotting horizontal lines in Matplotlib was one of the fundamental skills I needed.

In this guide, I’ll share my firsthand experience with several methods to draw horizontal lines in Matplotlib. I’ll keep it simple, practical, and focused on real-world examples relevant to data analysts and developers in the USA.

Let’s get in!

Methods to Draw Horizontal Lines in Matplotlib

Horizontal lines are useful for:

  • Showing benchmarks like average sales or revenue targets.
  • Indicating thresholds such as temperature limits or stock price alerts.
  • Highlighting specific values on charts for better readability.

For instance, if you’re analyzing monthly sales data across different states in the USA, drawing a horizontal line at the national average sales can instantly show which states are performing above or below average.

1: Use axhline() to Draw a Horizontal Line

The easiest and most direct way I use to draw a horizontal line is the axhline() method in Python. This method draws a horizontal line across the entire width of the axes at a specified y-value.

Here’s a quick example:

import matplotlib.pyplot as plt

# Sample monthly sales data for a USA-based retail company
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
sales = [25000, 27000, 30000, 28000, 32000, 31000]

plt.plot(months, sales, marker='o')

# Draw a horizontal line at the average sales value
average_sales = sum(sales) / len(sales)
plt.axhline(y=average_sales, color='r', linestyle='--', label='Average Sales')

plt.title('Monthly Sales with Average Line')
plt.xlabel('Month')
plt.ylabel('Sales ($)')
plt.legend()
plt.show()

You can refer to the screenshot below to see the output.

matplotlib horizontal line

Why I like axhline(): It’s easy and automatically spans the entire plot width. You can customize color, line style, and thickness easily.

Read Matplotlib Not Showing Plot

2: Use hlines() for More Control

Sometimes, you want to draw horizontal lines that don’t span the entire plot but only a specific range on the x-axis. That’s where hlines() comes in handy.

Here’s how I used it to highlight a sales target range between March and May:

plt.plot(months, sales, marker='o')

# Draw a horizontal line from March to May at the sales target of 29000
plt.hlines(y=29000, xmin=2, xmax=4, colors='g', linestyles='-', label='Sales Target')

plt.title('Monthly Sales with Target Range')
plt.xlabel('Month')
plt.ylabel('Sales ($)')
plt.legend()
plt.show()

You can refer to the screenshot below to see the output.

plot horizontal line matplotlib

Note: The xmin and xmax parameters use numeric indices of the x-axis. Since months are categorical, you can map them to their indices (e.g., Jan=0, Feb=1, Mar=2, etc.).

Check out Matplotlib Multiple Plots

3: Use plot() to Draw Horizontal Lines Manually

If you want full control or prefer a more manual approach, you can use the plot() function in Python to draw horizontal lines by specifying x and y coordinates.

For example, to draw a horizontal line at $30,000 sales from January to June:

plt.plot(months, sales, marker='o')

# Draw horizontal line manually
plt.plot([0, 5], [30000, 30000], color='orange', linestyle='-.', label='Goal')

plt.title('Monthly Sales with Goal Line')
plt.xlabel('Month')
plt.ylabel('Sales ($)')
plt.legend()
plt.show()

You can refer to the screenshot below to see the output.

horizontal line matplotlib

Here, [0, 5] corresponds to the x-axis positions for January (index 0) through June (index 5).

Customize Horizontal Lines

From my experience, customizing horizontal lines can make your plots more effective:

  • Color: Use contrasting colors to make lines stand out.
  • Line Style: Dashed ('--'), dotted (':'), or dash-dot ('-.') lines can differentiate lines.
  • Line Width: Thicker lines draw more attention.
  • Labels: Always add labels and legends for clarity.

Example:

plt.axhline(y=average_sales, color='blue', linestyle=':', linewidth=2, label='Avg Sales')

Real-World Example: Highlight Temperature Thresholds

Suppose you’re analyzing daily temperatures across New York City for a week, and you want to highlight the freezing point (32°F).

days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
temps = [30, 35, 28, 40, 42, 33, 31]

plt.plot(days, temps, marker='o')

# Freezing point line
plt.axhline(y=32, color='cyan', linestyle='--', label='Freezing Point')

plt.title('NYC Daily Temperatures')
plt.xlabel('Day')
plt.ylabel('Temperature (°F)')
plt.legend()
plt.show()

This instantly tells you which days dipped below freezing.

Check out Matplotlib Legend Font Size

Tips from My Experience

  • When working with categorical x-axis data (like months or days), remember to map categories to numeric indices if needed.
  • Use axhline() for full-width lines and hlines() if you want to restrict the line to a portion of the x-axis.
  • For interactive plots or dashboards, consider adding horizontal lines dynamically to highlight thresholds.

Drawing horizontal lines in Matplotlib is a simple yet useful way to enhance your visualizations. Whether you’re analyzing sales data, weather trends, or any other metric, these methods will help you communicate insights.

Other Matplotlib tutorials you may read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.