Plot Multiple Horizontal Lines in Matplotlib using Python

When I first started working with Python for data visualization, I often needed to highlight thresholds or reference levels in my charts. One of the simplest ways to do this is by adding horizontal lines.

I’ve used horizontal lines in Matplotlib countless times. Whether I was analyzing stock prices, visualizing air quality data, or building dashboards for U.S. business clients, horizontal lines helped me make my plots more meaningful.

In this tutorial, I’ll show you how to draw multiple horizontal lines in Matplotlib using Python. I’ll walk you through different methods, share complete code examples, and explain each step in simple terms.

Methods to Use Multiple Horizontal Lines in Python Matplotlib

When working with real-world datasets, horizontal lines can be used for:

  • Marking thresholds (e.g., U.S. EPA air quality standards for PM2.5 or ozone levels).
  • Highlighting averages or medians in survey data.
  • Adding reference points in financial charts, such as support and resistance levels.
  • Visualizing passing/failing scores in academic performance datasets.

These lines make your charts easier to interpret and more visually appealing.

Method 1 – Use axhline() in Python Matplotlib

The first method I usually use is axhline(). This function in Matplotlib allows us to draw a horizontal line across the entire width of the plot.

Here’s an example where I plot U.S. air quality index (AQI) values for a week and add multiple horizontal lines to indicate different air quality categories.

import matplotlib.pyplot as plt

# Sample AQI data for a U.S. city (daily values for one week)
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
aqi_values = [45, 60, 82, 110, 95, 130, 150]

# Create the plot
fig, ax = plt.subplots(figsize=(8, 5))
ax.plot(days, aqi_values, marker='o', linestyle='-', color='blue', label="Daily AQI")

# Add multiple horizontal lines for AQI categories
ax.axhline(y=50, color='green', linestyle='--', linewidth=1.5, label="Good (50)")
ax.axhline(y=100, color='orange', linestyle='--', linewidth=1.5, label="Moderate (100)")
ax.axhline(y=150, color='red', linestyle='--', linewidth=1.5, label="Unhealthy (150)")

# Add labels and title
ax.set_title("U.S. City Air Quality Index with Threshold Lines", fontsize=14)
ax.set_xlabel("Day of the Week")
ax.set_ylabel("AQI Value")
ax.legend()

# Show the plot
plt.show()

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

Multiple Horizontal Lines in Matplotlib using Python

In this example, I added three horizontal lines at AQI values of 50, 100, and 150. These represent thresholds defined by the U.S. Environmental Protection Agency.

Method 2 – Use hlines() in Python Matplotlib

Another powerful method is hlines(). Unlike axhline(), which draws a single line across the full width, hlines() allows us to draw multiple horizontal lines at once by passing a list of y-values.

Here’s an example where I plot average math test scores for students in a U.S. school district and add horizontal lines for passing and honors thresholds.

import matplotlib.pyplot as plt

# Sample student scores
students = ["Alice", "Bob", "Charlie", "David", "Ella", "Frank"]
scores = [78, 85, 92, 67, 88, 95]

# Create the plot
fig, ax = plt.subplots(figsize=(8, 5))
ax.bar(students, scores, color='skyblue', label="Scores")

# Add multiple horizontal lines
thresholds = [70, 90]  # Passing and Honors
ax.hlines(y=thresholds, xmin=-0.5, xmax=5.5, colors=['red', 'green'], linestyles='dashed')

# Add labels and title
ax.set_title("Student Test Scores with Threshold Lines", fontsize=14)
ax.set_xlabel("Students")
ax.set_ylabel("Score")

# Show the plot
plt.show()

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

Multiple Horizontal Lines in Matplotlib Python

Here, I used hlines() to add two horizontal lines: one at 70 (passing score) and one at 90 (honors score). This method is efficient when you want to add several lines at once.

Method 3 – Add Horizontal Lines with Labels in Python

Sometimes, I want to include labels directly on the horizontal lines for better clarity. This is especially useful in presentations or reports.

import matplotlib.pyplot as plt

# Sample daily sales data (in USD)
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
sales = [1200, 1500, 1700, 1600, 2000, 2200, 2500]

# Create the plot
fig, ax = plt.subplots(figsize=(8, 5))
ax.plot(days, sales, marker='o', linestyle='-', color='purple', label="Daily Sales")

# Add horizontal lines with labels
lines = [(1500, "Target"), (2000, "Stretch Goal")]
for y, label in lines:
    ax.axhline(y=y, color='gray', linestyle='--')
    ax.text(len(days)-0.5, y+20, label, color='black', fontsize=10)

# Add labels and title
ax.set_title("Weekly Sales with Target Lines", fontsize=14)
ax.set_xlabel("Day of the Week")
ax.set_ylabel("Sales (USD)")
ax.legend()

# Show the plot
plt.show()

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

Plot Multiple Horizontal Lines in Matplotlib Python

In this example, I added two horizontal lines, one for the sales target and another for the stretch goal. I also placed text labels right next to the lines.

Method 4 – Multiple Horizontal Lines from Data Arrays

In real projects, I often work with NumPy arrays or Pandas DataFrames. With these, I can easily create multiple horizontal lines dynamically.

import matplotlib.pyplot as plt
import numpy as np

# Simulated stock prices for a U.S. company
days = np.arange(1, 11)
prices = [150, 152, 148, 155, 160, 162, 158, 165, 170, 175]

# Create the plot
fig, ax = plt.subplots(figsize=(8, 5))
ax.plot(days, prices, marker='o', color='blue', label="Stock Price")

# Dynamic horizontal lines (mean and std deviation)
mean_price = np.mean(prices)
std_dev = np.std(prices)

ax.axhline(y=mean_price, color='green', linestyle='--', label=f"Mean ({mean_price:.2f})")
ax.axhline(y=mean_price + std_dev, color='orange', linestyle='--', label="Mean + 1 Std Dev")
ax.axhline(y=mean_price - std_dev, color='red', linestyle='--', label="Mean - 1 Std Dev")

# Add labels and title
ax.set_title("Stock Prices with Statistical Reference Lines", fontsize=14)
ax.set_xlabel("Day")
ax.set_ylabel("Price (USD)")
ax.legend()

# Show the plot
plt.show()

Here, I calculated the mean and standard deviation of stock prices and used them to draw three horizontal lines.

Best Practices When Adding Multiple Horizontal Lines

Over the years, I’ve learned a few best practices when working with horizontal lines in Python Matplotlib:

  • Use consistent colors and styles for thresholds (e.g., red for danger, green for safe).
  • Add labels or a legend so viewers understand what each line represents.
  • Avoid cluttering the chart with too many lines; focus on the most important ones.
  • Use dashed lines to differentiate reference lines from actual data plots.

These small details make your charts more professional and easier to interpret.

When I look back at my early Python projects, I realize how much clarity horizontal lines added to my visualizations. They are simple yet powerful tools for storytelling with data.

Now that you know different methods, axhline(), hlines(), labeled lines, and dynamic lines, you can apply them in your own projects. Whether you’re analyzing U.S. stock prices, student scores, or sales data, multiple horizontal lines in Matplotlib will help you communicate insights more effectively.

You may also read other tutorials on Matplotlib:

Leave a Comment

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.