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

How to Efficiently Create Multiple Subplots in Matplotlib?

Linda Hamilton
Linda HamiltonOriginal
2024-12-28 06:50:34176browse

How to Efficiently Create Multiple Subplots in Matplotlib?

Ploting in Multiple Subplots

Creating multiple subplots in Matplotlib poses a challenge to some users. Let's delve into how to accomplish this task effectively.

Subplots() Method

The subplots() method provides a straightforward approach to generate subplots. It creates both the figure and the subplots, which are subsequently stored in an axes array.

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

This code generates a 2x2 grid of subplots, with each subplot containing a line plot of x and y.

Figure and Subplots Separation

While the subplots() method combines figure and subplot creation, it's possible to separate these functions:

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

However, this approach is less organized, as subplots are added onto an existing figure.

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

Statement:
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