Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
World desk3 min

How to Plot Multiple Graphs Generated Inside a For Loop in Matplotlib

Use one Matplotlib Axes for multiple lines, a subplot grid for separate panels, or create and close individual figures when outputs must stand alone.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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.

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).

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

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.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.