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

How to Efficiently Create Multiple Subplots in Matplotlib?

Linda Hamilton
Release: 2024-12-28 06:50:34
Original
207 people have browsed it

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()
Copy after login

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()
Copy after login

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!

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