The Tool Desk
Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →First decide whether you want several lines on one graph or a separate graph for each dataset. For one graph per dataset, create a figure and subplot axes with plt.subplots, then plot each dataset on its matching axes. For multiple lines on one graph, create one axes and call its plot method repeatedly.
Plot multiple lines on one graph
Use one Axes and call ax.plot() for each series in the loop. Each call adds a line to the same plotting area, which is useful when the series share a scale and you want to compare them directly.
import matplotlib.pyplot as plt
datasets = [(x1, y1), (x2, y2), (x3, y3)]
fig, ax = plt.subplots()
for x, y in datasets:
ax.plot(x, y)
plt.show()
If readers need to distinguish the lines, give each call a label and add ax.legend(). You can also set titles and axis labels through the same axes object, such as ax.set_xlabel("x") and ax.set_ylabel("y").
Put each dataset in its own subplot
A Matplotlib Figure can contain multiple Axes; each Axes is an individual plotting area. Create the subplot grid once, then pair each dataset with an axes and call that axes’ plotting method. The official subplot example uses axs.flat to iterate across a grid.
Recommended Free Tools
#1 Best Overall
import matplotlib.pyplot as plt
datasets = [(x1, y1), (x2, y2), (x3, y3)]
fig, axs = plt.subplots(1, len(datasets), squeeze=False)
for ax, (x, y) in zip(axs.flat, datasets):
ax.plot(x, y)
ax.set_xlabel("x")
ax.set_ylabel("y")
fig.tight_layout()
plt.show()
squeeze=False makes axs a two-dimensional array even when there is only one row or column, so axs.flat works for a single subplot as well as a grid. By default, plt.subplots may instead return a single Axes object for one subplot and an array for multiple subplots; the exact return shape depends on the requested rows, columns, and squeeze setting. See the subplots API.
Make the grid fit the data
The example creates one subplot per dataset in a single row. For a larger set, choose appropriate row and column counts, for example plt.subplots(rows, cols, squeeze=False), and iterate over axs.flat. Ensure the grid has enough axes: zip(axs.flat, datasets) stops when either iterable runs out, so extra datasets would otherwise be left unplotted without an error. If the number of datasets is unknown, calculate the grid dimensions from the data count or create axes as needed rather than relying on a fixed grid.
Rank #2
Handle a single subplot safely
When you use the default squeeze=True, a one-subplot call returns a scalar Axes rather than an array. Code such as axs[i] therefore fails for one dataset. Use squeeze=False, normalize the axes object to an array, or explicitly handle the single-Axes case.
Create a separate figure for every loop iteration
Use a new figure inside the loop only when each output should be viewed or saved independently, rather than compared in one shared figure. Close figures that are no longer needed so pyplot can release them; Matplotlib’s figure API documents plt.close(fig).
import matplotlib.pyplot as plt
for i, (x, y) in enumerate(datasets):
fig, ax = plt.subplots()
ax.plot(x, y)
fig.savefig(f"plot_{i}.png")
plt.close(fig)
Call fig.savefig(...) before closing the figure. To display figures interactively, use plt.show(); notebook environments may display figures automatically.
Why use an Axes object in the loop?
Calls such as ax.plot(), ax.set_title(), and ax.set_xlabel() make the target subplot explicit. Pyplot also provides state-based plotting calls, but Matplotlib’s pyplot documentation recommends the explicit object-oriented API for complex plots. In a loop, using each axes object directly avoids relying on whichever axes pyplot currently considers active.
Quick Recap
Best Value
Choose the right loop pattern
| Goal | Pattern | Key consideration |
|---|---|---|
| Several series on one graph | Create one fig, ax = plt.subplots() and call ax.plot() for each series. |
All lines share the same axes; add labels and a legend when needed. |
| One graph per dataset in a combined figure | Create a grid with plt.subplots(rows, cols) and pair datasets with axes. |
Choose enough axes and account for the return shape. |
| Independent output files or windows | Create a figure per iteration, save or show it, then close it when finished. | Manage each figure’s lifetime with plt.close(fig). |
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




