Home > Backend Development > Python Tutorial > How to Efficiently Create and Plot in Multiple Matplotlib Subplots?

How to Efficiently Create and Plot in Multiple Matplotlib Subplots?

Susan Sarandon
Release: 2024-12-20 13:57:09
Original
814 people have browsed it

How to Efficiently Create and Plot in Multiple Matplotlib Subplots?

Plotting in Multiple Subplots

Creating multiple subplots in Matplotlib can be achieved through various methods. Understanding the role of the fig and axes variables is crucial.

The fig, axes Structure

In the code snippet fig, axes = plt.subplots(nrows=2, ncols=2), fig and axes are assigned to the returned figure and a 2D array of Axes objects, respectively. The axes array contains the individual subplots, enabling subsequent plotting operations on specific subplots.

Alternatives to subplots

While the subplots method simultaneously creates a figure and its subplots, it's also possible to create them separately:

fig = plt.figure()
axes = fig.subplots(nrows=2, ncols=2)
Copy after login

However, this approach is less preferred because it requires additional steps to plot on each subplot.

Example with Multiple Subplots

Consider the following code that plots a simple curve on each of the four subplots:

import matplotlib.pyplot as plt

x = range(10)
y = range(10)

fig, ax = plt.subplots(nrows=2, ncols=2)

for row in ax:
    for col in row:
        col.plot(x, y)

plt.show()
Copy after login

This code generates a figure with four subplots, each with the same curve. The for loops iterate over the rows and columns of the ax array, assigning each subplot to the col variable for plotting.

Another Alternative Approach

Though not as elegant, one can also manually create and plot on each subplot separately:

fig = plt.figure()

plt.subplot(2, 2, 1)
plt.plot(x, y)

plt.subplot(2, 2, 2)
plt.plot(x, y)

plt.subplot(2, 2, 3)
plt.plot(x, y)

plt.subplot(2, 2, 4)
plt.plot(x, y)

plt.show()
Copy after login

This approach involves creating a figure, manually specifying each subplot's position, and then plotting on them.

The above is the detailed content of How to Efficiently Create and Plot in Multiple Matplotlib Subplots?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template