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