HOWTO · Matplotlib

How to Overlay Plots in Matplotlib

This article describes how to overlay plots in Matplotlib, providing practical examples and clear explanations. Learn the best methods to combine different types of visualizations, including line and bar plots, to enhance your data storytelling. Discover how to create layered graphics that effectively communicate insights and comparisons.

On this page

To overlay plots in Matplotlib, draw each dataset on the same Axes object. This lets you compare related values in one coordinate system. Use separate subplots when the datasets need distinct scales or are easier to read apart; each subplot has its own Axes.

Method 1: Basic Overlay of Line Plots

Call plot() more than once on the same axes. The following example compares sine and cosine values at matching x positions. Each call adds a line, and the labels provide entries for one legend.

Run this example in an environment with a Matplotlib display; it opens the figure and saves line-overlay.png in the current directory. In a headless environment, the saved PNG still provides the result.

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
fig, ax = plt.subplots()
ax.plot(x, np.sin(x), label="Sine", color="blue")
ax.plot(x, np.cos(x), label="Cosine", color="red")
ax.set(title="Sine and cosine", xlabel="x", ylabel="Value")
ax.legend()
fig.savefig("line-overlay.png", dpi=150, bbox_inches="tight")
plt.show()
plt.close(fig)

Overlayed Plot in Matplotlib

Both lines share the same x and y scales, so the graph makes their values at each x position easy to compare. If the series have different units or very different ranges, a shared y-axis can mislead; consider separate subplots or a clearly labeled secondary axis instead.

Method 2: Overlaying Bar and Line Plots

Bars and a line can share an axes when they refer to the same categories and their values are meaningfully comparable. Use numeric category positions so the markers land at the centers of the bars. Bar transparency can help the line remain visible.

Run this example; it opens the figure and saves bar-line-overlay.png in the current directory.

import matplotlib.pyplot as plt

categories = ["A", "B", "C", "D"]
positions = range(len(categories))
bar_values = [3, 7, 2, 5]
line_values = [4, 6, 3, 4]

fig, ax = plt.subplots()
ax.bar(positions, bar_values, width=0.65, alpha=0.55, label="Bar values")
ax.plot(positions, line_values, color="darkorange", marker="o", label="Line values")
ax.set_xticks(list(positions), categories)
ax.set(xlabel="Category", ylabel="Value", title="Bar and line overlay")
ax.legend()
fig.savefig("bar-line-overlay.png", dpi=150, bbox_inches="tight")
plt.show()
plt.close(fig)

Overlaying Bar and Line Plots

This example uses one y-axis because the two series are on a comparable scale. If one series measures a different quantity or unit, describe that clearly and use separate axes or subplots to avoid suggesting that the heights are directly comparable.

Control Which Plot Appears in Front with zorder

Matplotlib draws artists in zorder order: a larger value is drawn in front of a smaller one. Set it explicitly when a line should remain visible over bars. Run this example; it opens the figure and saves zorder-overlay.png in the current directory.

import matplotlib.pyplot as plt

positions = [0, 1, 2]
fig, ax = plt.subplots()
ax.bar(positions, [3, 5, 4], alpha=0.6, zorder=1)
ax.plot(positions, [4, 3, 5], color="darkorange", marker="o", zorder=2)
fig.savefig("zorder-overlay.png", dpi=150, bbox_inches="tight")
plt.show()
plt.close(fig)

A higher zorder controls drawing order, not the numerical scale or data values. It is useful for making markers or grid lines visible, but it cannot resolve overlapping data that needs different scales.

Method 3: Using Subplots to Organize Multiple Plots

plt.subplots() creates separate axes. You can overlay related series within one subplot while placing a different series in another, as shown here. This keeps distinct comparisons organized without implying that every dataset shares one scale.

Run this example; it opens the figure and saves subplot-overlay.png in the current directory:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
fig, axes = plt.subplots(2, 1, figsize=(8, 6))
axes[0].plot(x, np.sin(x), label="Sine")
axes[0].plot(x, np.cos(x), label="Cosine")
axes[0].set_ylabel("Value")
axes[0].legend()
tangent = np.tan(x)
tangent[np.abs(tangent) > 5] = np.nan
axes[1].plot(x, tangent, color="green", label="Tangent")
axes[1].set_ylim(-5, 5)
axes[1].set_xlabel("x")
axes[1].set_ylabel("Value")
axes[1].legend()
fig.tight_layout()
fig.savefig("subplot-overlay.png", dpi=150, bbox_inches="tight")
plt.show()
plt.close(fig)

The first axes contains two overlaid lines; the second contains tangent segments within the displayed y range. Values whose magnitude exceeds 5 are masked before plotting, so Matplotlib does not draw line segments across the tangent function’s vertical asymptotes. tight_layout() adjusts spacing so labels are less likely to overlap. For many datasets, add subplots only when they help distinguish comparisons; a dense overlay can be harder to interpret than a small set of focused charts.

Conclusion

Overlay plots in Matplotlib by calling plotting methods on the same Axes. Use a legend, clear labels, compatible scales, and zorder when draw order matters. Choose separate subplots when data should remain distinct, and keep the number of overlaid series small enough to read.

FAQ

  1. Why overlay plots in Matplotlib?
    An overlay places related datasets in one view, making trends and values easier to compare when they share meaningful scales.

  2. Can I combine different plot types?
    Yes. For example, draw bars and a line on the same axes when their categories and values can be compared clearly.

  3. How can I customize overlaid plots?
    Set colors, markers, line styles, transparency, labels, and zorder in the plotting calls. Keep the legend and axis labels specific to each series.

  4. How many plots can I overlay?
    There is no fixed limit, but many lines or marks can clutter the chart. Split the data into subplots when labels or comparisons become difficult to follow.

  5. How do I save an overlay as an image?
    Call fig.savefig("overlay.png", dpi=150, bbox_inches="tight") before closing the figure. This saves the current figure to a PNG file; choose another supported file extension when needed.