Add Horizontal Line in Matplotlib Subplots

While I was working on a Python project, I needed to highlight certain thresholds across multiple charts. I was using Matplotlib subplots to show different datasets side by side, and I wanted to add a horizontal line in each subplot to mark a reference value.

At first, I thought there would be a quick one-click option to do this. But just like in Excel, where some formatting requires a workaround, in Matplotlib, you need to use the right functions to get the job done.

In this tutorial, I will share the exact methods I use to add horizontal lines in Matplotlib subplots. I’ll cover different approaches such as axhline(), hlines(), and even looping through multiple subplots.

Why Add a Horizontal Line in Python Matplotlib?

When working with charts, a horizontal line can be very useful. It acts as a reference marker. For example:

  • In finance, you may want to mark the average stock price across multiple charts.
  • In healthcare data, you might highlight a threshold such as a blood pressure level.
  • In productivity analysis, you could show a target value, like the average number of tasks completed per day.

Adding a horizontal line in Matplotlib subplots makes it easier for your audience to quickly see how the data compares against important benchmarks.

Method 1 – Use axhline() in Python Matplotlib Subplots

The simplest way to add a horizontal line in Matplotlib is by using the axhline() function. This function draws a line across the entire width of the subplot at a specified y-value.

Here’s a complete example in Python where I create two subplots and add a horizontal line at y=50 in both.

import matplotlib.pyplot as plt
import numpy as np

# Sample data
x = np.linspace(0, 10, 100)
y1 = np.random.randint(30, 70, 100)
y2 = np.random.randint(40, 90, 100)

# Create subplots
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 5))

# Plot data
ax1.plot(x, y1, color='blue')
ax2.plot(x, y2, color='green')

# Add horizontal line at y=50
ax1.axhline(y=50, color='red', linestyle='--', linewidth=2)
ax2.axhline(y=50, color='red', linestyle='--', linewidth=2)

# Add titles
ax1.set_title("Dataset 1")
ax2.set_title("Dataset 2")

plt.tight_layout()
plt.show()

I executed the above example code and added the screenshot below.

Horizontal Line in Matplotlib Subplots

In this code, I used axhline() for both subplots. The red dashed line at y=50 clearly marks the threshold across both charts.

This method is quick and works perfectly when you want the same horizontal line across multiple subplots.

Method 2 – Use hlines() in Python Matplotlib

Another way to add a horizontal line is by using the hlines() function. Unlike axhline(), which spans the entire axis, hlines() allows you to control the start (xmin) and end (xmax) of the line.

This is useful if you want the line to cover only part of the subplot.

import matplotlib.pyplot as plt
import numpy as np

# Sample data
x = np.linspace(0, 20, 200)
y = np.sin(x) * 50 + 50

# Create subplot
fig, ax = plt.subplots(figsize=(8, 5))

# Plot data
ax.plot(x, y, color='purple')

# Add horizontal line from x=5 to x=15 at y=50
ax.hlines(y=50, xmin=5, xmax=15, colors='red', linestyles='dashed', linewidth=2)

# Title
ax.set_title("Horizontal Line with hlines()")

plt.show()

I executed the above example code and added the screenshot below.

Horizontal Line in Python Matplotlib Subplots

Here, the horizontal line only appears between x=5 and x=15. This gives you more flexibility when working with subplots where you don’t always want the line to span the full width.

Method 3 – Loop Through Multiple Subplots in Python

When you have many subplots, adding horizontal lines manually can be repetitive. A better approach is to loop through all subplots and add the line automatically.

This is especially useful when working with dashboards or reports where you need consistent reference lines across multiple charts.

import matplotlib.pyplot as plt
import numpy as np

# Generate sample data
x = np.linspace(0, 10, 100)

datasets = [np.random.randint(20, 80, 100),
            np.random.randint(30, 90, 100),
            np.random.randint(10, 70, 100)]

# Create subplots
fig, axes = plt.subplots(1, 3, figsize=(15, 4))

# Plot each dataset
for ax, data in zip(axes, datasets):
    ax.plot(x, data, color='blue')
    ax.axhline(y=50, color='red', linestyle='--', linewidth=2)
    ax.set_title("Dataset Plot")

plt.tight_layout()
plt.show()

I executed the above example code and added the screenshot below.

Add Horizontal Line in Python Matplotlib Subplots

In this code, I looped through three subplots and added the same horizontal line (y=50) to each. This method saves time and ensures consistency when working with multiple datasets.

Method 4 – Add Multiple Horizontal Lines in Subplots

Sometimes, you may want to add more than one horizontal line in a subplot. For example, you might want to highlight both a minimum and a maximum threshold.

import matplotlib.pyplot as plt
import numpy as np

# Sample data
x = np.linspace(0, 10, 100)
y = np.random.randint(20, 100, 100)

# Create subplot
fig, ax = plt.subplots(figsize=(8, 5))

# Plot data
ax.plot(x, y, color='black')

# Add multiple horizontal lines
ax.axhline(y=30, color='green', linestyle='--', linewidth=2, label='Min Threshold')
ax.axhline(y=70, color='red', linestyle='--', linewidth=2, label='Max Threshold')

# Add legend
ax.legend()

# Title
ax.set_title("Multiple Horizontal Lines in Matplotlib Subplot")

plt.show()

I executed the above example code and added the screenshot below.

Add Horizontal Line in Matplotlib Subplots in Python

Here, I added two horizontal lines at y=30 and y=70. This is a common use case when you want to show acceptable ranges in your data.

Method 5 – Customize Horizontal Lines in Python

Matplotlib gives you full control over how the horizontal lines look. You can customize:

  • Color (color=’blue’)
  • Style (linestyle=’dotted’, linestyle=’dashdot’)
  • Width (linewidth=3)
  • Transparency (alpha=0.5)

Here’s an example with different styles:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y = np.random.randint(10, 90, 100)

fig, ax = plt.subplots(figsize=(8, 5))
ax.plot(x, y)

# Different styles of horizontal lines
ax.axhline(y=40, color='blue', linestyle='-', linewidth=2, alpha=0.7)
ax.axhline(y=60, color='orange', linestyle='dotted', linewidth=3)
ax.axhline(y=80, color='purple', linestyle='dashdot', linewidth=2)

ax.set_title("Custom Horizontal Lines in Python Matplotlib")

plt.show()

Customizing your horizontal lines makes your charts more professional and easier to understand.

Practical Example – Add a Target Line in Sales Data

Let’s take a practical example relevant to the USA market. Suppose you’re analyzing monthly sales data for three different regions. You want to show a horizontal line at the target sales value of 500 units.

import matplotlib.pyplot as plt
import numpy as np

# Sample monthly sales data
months = np.arange(1, 13)
region1 = np.random.randint(400, 600, 12)
region2 = np.random.randint(450, 650, 12)
region3 = np.random.randint(300, 700, 12)

# Create subplots
fig, axes = plt.subplots(1, 3, figsize=(15, 5))

# Plot sales data with target line
for ax, data, title in zip(axes, [region1, region2, region3], ["Region 1", "Region 2", "Region 3"]):
    ax.plot(months, data, marker='o')
    ax.axhline(y=500, color='red', linestyle='--', linewidth=2, label='Target Sales')
    ax.set_title(title)
    ax.set_xlabel("Month")
    ax.set_ylabel("Sales")
    ax.legend()

plt.tight_layout()
plt.show()

In this chart, the red dashed line at y=500 clearly shows whether each region met or missed the sales target. This is a real-world example of how horizontal lines in Matplotlib subplots can make your analysis more actionable.

Adding a horizontal line in Matplotlib subplots is not complicated once you know the right methods. I showed you how to use axhline(), hlines(), loops for multiple subplots, and even how to add multiple or customized lines.

Personally, I use axhline() most often because it’s quick and works well for most cases. But when I need more control, hlines() and loops save me a lot of time.

Next time you’re working on a Python project and need to highlight thresholds or targets, try one of these methods. It will make your charts more professional and easier for others to understand.

You may also read:

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.