Matplotlib Horizontal Line with Text in Python

As part of a Python project, I wanted to highlight a specific threshold in my chart. I needed to draw a horizontal line and add text to explain what that line represented.

The problem was that while drawing a horizontal line in Matplotlib is easy, adding text in the right place can be tricky for beginners.

In this article, I’ll share the exact methods I use to add a horizontal line with text in Matplotlib. These methods are simple, practical, and will work for real-world Python projects.

Method 1 – Use axhline() with text()

The first and easiest method is to use the axhline() function in Matplotlib to draw the horizontal line and then use the text() function to add a label.

This approach works well when you want a quick solution for simple plots.

import matplotlib.pyplot as plt

# Sample data for monthly sales in the USA
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
sales = [1200, 1500, 1700, 1600, 1800, 2000]

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

# Draw a horizontal line at the sales target
plt.axhline(y=1600, color='red', linestyle='--')

# Add text to explain the line
plt.text(x=0.5, y=1610, s="Target Sales = 1600", color='red')

# Add labels and title
plt.title("Monthly Sales in the USA")
plt.xlabel("Month")
plt.ylabel("Sales")

# Show the plot
plt.show()

You can see the output in the screenshot below.

Matplotlib Horizontal Line with Text in Python

In this example, I used axhline() to create a dashed red line at the sales target of 1600. Then, I added a text label slightly above the line to make it clear what it represents.

Method 2 – Use hlines() with annotate()

Another method I often use is hlines() combined with annotate(). This is useful when you want more control over the positioning of the text relative to the line.

import matplotlib.pyplot as plt

# Data: average daily temperature in New York City (°F)
days = range(1, 8)
temperature = [32, 35, 40, 45, 50, 55, 60]

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

# Add a horizontal line at freezing point
plt.hlines(y=32, xmin=1, xmax=7, colors='blue', linestyles='dotted')

# Annotate the line with text
plt.annotate("Freezing Point (32°F)", 
             xy=(7, 32), 
             xytext=(5, 34), 
             arrowprops=dict(facecolor='black', shrink=0.05))

plt.title("Average Daily Temperature in NYC")
plt.xlabel("Day of the Week")
plt.ylabel("Temperature (°F)")

plt.show()

You can see the output in the screenshot below.

Horizontal Line with Text in Python

Here, I used hlines() to draw the line across the x-axis range. The annotate() function allows me to add text with an arrow pointing directly to the line.

This method is more flexible and works well when you want your charts to look polished and professional.

Method 3 – Add Multiple Horizontal Lines with Text

Sometimes you may need to show multiple thresholds or levels in the same chart. In that case, you can combine axhline() calls with multiple text() labels.

import matplotlib.pyplot as plt

# Data: student test scores in a US school
students = ["A", "B", "C", "D", "E", "F"]
scores = [65, 78, 90, 55, 88, 72]

plt.bar(students, scores, color='skyblue')

# Pass/Fail threshold
plt.axhline(y=60, color='red', linestyle='--')
plt.text(x=0.2, y=62, s="Pass Mark = 60", color='red')

# Honors threshold
plt.axhline(y=85, color='green', linestyle='--')
plt.text(x=0.2, y=87, s="Honors = 85", color='green')

plt.title("Student Test Scores in USA School")
plt.xlabel("Students")
plt.ylabel("Scores")

plt.show()

You can see the output in the screenshot below.

Horizontal Line with Text in Python Matplotlib

In this example, I plotted student test scores and added two horizontal lines: one for the pass mark and another for honors. Each line has its own text label.

Method 4 – Use axhline() with Dynamic Text Placement

When working with dynamic data, you may not know in advance where to place the text. In such cases, you can calculate the position programmatically.

import matplotlib.pyplot as plt
import numpy as np

# Simulated stock prices for a US company
days = np.arange(1, 11)
prices = [150, 152, 148, 153, 155, 158, 160, 162, 159, 161]

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

# Draw average price line
avg_price = np.mean(prices)
plt.axhline(y=avg_price, color='purple', linestyle='--')

# Place text dynamically at the middle of the x-axis
mid_x = (days[0] + days[-1]) / 2
plt.text(mid_x, avg_price + 1, f"Average Price = {avg_price:.2f}", color='purple')

plt.title("Stock Prices of a US Company")
plt.xlabel("Day")
plt.ylabel("Price ($)")

plt.show()

You can see the output in the screenshot below.

Python Matplotlib Horizontal Line with Text

Here, I calculated the average stock price and placed the text label at the midpoint of the x-axis. This way, the text always appears in the right spot regardless of the data size.

Method 5 – Horizontal Line with Text in Subplots

If you’re working with multiple subplots, you can add horizontal lines with text to each subplot individually.

import matplotlib.pyplot as plt

# Data for two US cities
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
nyc_temps = [45, 48, 50, 55, 60, 62, 65]
la_temps = [60, 62, 65, 67, 70, 72, 75]

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))

# NYC subplot
ax1.plot(days, nyc_temps, marker='o')
ax1.axhline(y=50, color='red', linestyle='--')
ax1.text(1, 51, "Critical Temp = 50°F", color='red')
ax1.set_title("NYC Weekly Temps")

# LA subplot
ax2.plot(days, la_temps, marker='o', color='orange')
ax2.axhline(y=70, color='blue', linestyle='--')
ax2.text(1, 71, "Threshold = 70°F", color='blue')
ax2.set_title("LA Weekly Temps")

plt.suptitle("Weekly Temperature Trends in US Cities")
plt.show()

This method is great when you want to compare two or more datasets side by side and still highlight important thresholds.

Best Practices for Horizontal Lines with Text in Python

  • Always use contrasting colors for the line and text so they are easy to read.
  • Place text slightly above or below the line to avoid overlap.
  • Use annotate() when you need arrows or dynamic positioning.
  • Keep the text short and clear for better readability.
  • Test your chart with real-world data to ensure the annotations are visible.

Final Thoughts

Adding a horizontal line with text in Matplotlib is one of those small tricks that can make your charts much more informative.

I’ve shown you five different methods that I personally use in Python projects. Each method has its own strengths, and the one you choose will depend on your data and visualization goals.

If you’re creating quick plots, axhline() with text() is the fastest way. If you want polished visuals, hlines() with annotate() works best. For dynamic or multiple thresholds, you can mix and match these methods.

You may also like to 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.