# 5 Best Ways to Plot a Horizontal Line on Multiple Subplots in Python Using Pyplot

Rate this post

💡 Problem Formulation: When visualizing data with multiple subplots, it’s often necessary to highlight specific values across all plots for comparison. Python’s Pyplot from the Matplotlib library allows for such customizations. For instance, if you are analyzing temperature data across different cities, you might want to highlight a specific temperature threshold on multiple subplots. This article outlines five effective methods to plot a horizontal line across multiple subplots in Python.

## Method 1: Using `axhline` within Subplot Iteration

Iterating through each subplot and using the `axhline` method is the most straightforward way of adding horizontal lines to each subplot. This function draws a horizontal line at a specific y-axis value on a single Axes instance, which can be done for multiple Axes within a loop.

Here’s an example:

```import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=2, ncols=1)
for ax in axes:
ax.plot(range(10), range(10))
ax.axhline(y=5, color='r', linestyle='--')

plt.show()```

The output will be two subplots, each containing a red dashed horizontal line drawn at y=5.

This code snippet sets up a figure with two subplots (stacked vertically), iterates through these subplots, and plots a simple linear relationship between x and y. It then adds a horizontal line at y=5 with a dashed red line on each subplot using `ax.axhline()`.

## Method 2: Using `hlines` within Subplot Iteration

The `hlines` function adds a horizontal line across the axis at a specific position from a minimum x-value to a maximum x-value. When used within a subplot iteration, it can be applied to multiple subplots for marked values on the y-axis.

Here’s an example:

```import matplotlib.pyplot as plt

fig, axes = plt.subplots(2, 1)
for ax in axes:
ax.plot(range(10), range(10))
ax.hlines(y=5, xmin=0, xmax=9, colors='g', linestyles='dotted')

plt.show()```

The output will again be two subplots with green dotted horizontal lines at y=5 spanning the complete width of each subplot.

Here we’ve defined a figure with two subplots and then used a for-loop to plot a simple line on each subplot. We then used the `hlines` function to create a dotted green horizontal line at y=5 which spans the width of the plot from `xmin=0` to `xmax=9`.

## Method 3: Using a Shared Axes Parameter

By using the shared axes parameter when creating subplots, any alteration to one of the subplots, such as adding a horizontal line, will be applied to all the subplots automatically. This method is useful when all subplots share the same x or y-axis scale.

Here’s an example:

```import matplotlib.pyplot as plt

fig, axes = plt.subplots(2, 1, sharex=True, sharey=True)
axes[0].plot(range(10), range(10))
axes[0].axhline(y=5, color='b', linestyle='--')

plt.show()```

Your output will be two identical subplots with a blue dashed horizontal line at y=5.

The code creates two vertically stacked subplots that share both x and y axes. After plotting a line on the first subplot, we use `axhline` to draw a blue dashed horizontal line on it. Due to the shared axes parameter, this line appears on both subplots.

## Method 4: Using `GridSpec` with Horizontal Lines

`GridSpec` is a Matplotlib module that allows for more complex subplot layouts. It can be used in conjunction with horizontal line functions to place lines across multiple subplots created with variable-sized layout configurations.

Here’s an example:

```import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

fig = plt.figure(tight_layout=True)
gs = gridspec.GridSpec(2, 1)

for ax in [ax1, ax2]:
ax.plot(range(10), range(10))
ax.axhline(y=5, color='purple', linestyle=':')

plt.show()```

The result will be two subplots arranged according to the `GridSpec` layout, each with a purple dotted horizontal line at y=5.

Utilizing `GridSpec` allows for the creation of the subplots’ structure, after which we add a subplot per specified grid position. Each subplot receives a purple dotted horizontal line at y=5 using the `axhline` method.

## Bonus One-Liner Method 5: Horizontal Line across All Axes

Add a horizontal line across all subplots in a figure at once using a comprehension loop in Python. This is a concise and pythonic way to apply a function to all items in a list—in this case, subplots in a figure.

Here’s an example:

```import matplotlib.pyplot as plt

fig, axes = plt.subplots(2, 1)
[ax.axhline(y=5, color='orange', linestyle='-.') for ax in axes]

plt.show()```

Your output: two subplots each with an orange dash-dot horizontal line at y=5.

In this succinct snippet, a list comprehension is used to iterate through each axes object in one line of code. The `axhline` function is applied to each subplot directly within the comprehension.

## Summary/Discussion

• Method 1: Using `axhline` within Subplot Iteration. Strengths: intuitive and versatile. Weaknesses: can be verbose with many subplots.
• Method 2: Using `hlines` within Subplot Iteration. Strengths: control over horizontal line span. Weaknesses: more parameters required than `axhline`.
• Method 3: Using a Shared Axes Parameter. Strengths: simple and effective for subplots with shared axes. Weaknesses: limited to shared axis scenarios.
• Method 4: Using `GridSpec` with Horizontal Lines. Strengths: flexible for complex layouts. Weaknesses: requires understanding of GridSpec.
• Bonus Method 5: Horizontal Line across All Axes. Strengths: very concise code. Weaknesses: less explicit, might be confusing for beginners.