Home >Backend Development >Python Tutorial >How to Efficiently Create Multiple Subplots in Matplotlib?
Creating multiple subplots in Matplotlib poses a challenge to some users. Let's delve into how to accomplish this task effectively.
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.
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!