How to force errorbars to render last with Matplotlib?

When plotting multiple datasets in Matplotlib, you may want error bars to appear on top of other plot elements for better visibility. By default, plot elements are drawn in the order they're called, so error bars might be hidden behind other lines.

Default Behavior

Here's what happens when error bars are plotted before other lines −

import matplotlib.pyplot as plt
import numpy as np

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

fig = plt.figure()
ax = plt.gca()

# Error bars plotted first (will be hidden)
ax.errorbar(range(10), np.random.rand(10), yerr=0.3 * np.random.rand(10), 
            label='Data with errors', capsize=5)

# Multiple lines plotted after (will cover error bars)
for j in range(5):
    ax.plot(np.random.rand(10), alpha=0.7, linewidth=2)

ax.legend()
plt.title("Error bars hidden behind other lines")
plt.show()

Solution: Plot Error Bars Last

To force error bars to render on top, simply plot them after all other elements −

import matplotlib.pyplot as plt
import numpy as np

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

fig = plt.figure()
ax = plt.gca()

# Plot other lines first
for j in range(5):
    ax.plot(np.random.rand(10), alpha=0.7, linewidth=2)

# Plot error bars last (will appear on top)
ax.errorbar(range(10), np.random.rand(10), yerr=0.3 * np.random.rand(10), 
            label='Data with errors', capsize=5, color='red', linewidth=2)

ax.legend()
plt.title("Error bars rendered on top")
plt.show()

Using zorder Parameter

For more control, use the zorder parameter. Higher values render on top −

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(figsize=[7.50, 3.50])

# Plot lines with default zorder
for j in range(5):
    ax.plot(np.random.rand(10), alpha=0.7, linewidth=2)

# Force error bars to top with high zorder
ax.errorbar(range(10), np.random.rand(10), yerr=0.3 * np.random.rand(10), 
            label='Error bars on top', capsize=5, color='black', 
            linewidth=2, zorder=10)

ax.legend()
plt.title("Using zorder to control rendering order")
plt.show()

Comparison

Method Advantages Best For
Plot order Simple and intuitive Basic plots with few elements
zorder parameter Explicit control, works regardless of plot order Complex plots with many overlapping elements

Conclusion

To force error bars to render last, either plot them after other elements or use the zorder parameter with a high value. The zorder approach provides more explicit control over layering in complex visualizations.

Updated on: 2026-03-25T22:08:59+05:30

164 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements