Home >Backend Development >Python Tutorial >How do `fig` and `axes` Work in Matplotlib's `subplots()` Function?
Plotting in Multiple Subplots
Question:
In the following code, how do the fig and axes variables work when using subplots():
fig, axes = plt.subplots(nrows=2, ncols=2) plt.show()
Answer:
The subplots() method creates a figure (fig) and an array (axes) of subplot axes. Each subplot axis corresponds to a cell in the specified grid of subplots. In this case, the grid has 2 rows and 2 columns, resulting in 4 subplot axes stored in the axes array.
Reason for the Subplots Array:
subplots() is designed to simplify plotting in multiple subplots. Rather than creating separate figures and axes for each subplot manually, you can use subplots() to create a single figure containing multiple subplots. The axes array allows you to access and plot on each subplot axis individually.
Comparison with Alternative Approach:
The alternative approach mentioned in the question creates a figure (fig) and then calls fig.subplots() to create the subplots:
fig = plt.figure() axes = fig.subplots(nrows=2, ncols=2)
This approach is valid but less efficient than using subplots() directly because it requires two separate calls. Moreover, it is not necessary to assign the figure to a variable (fig) when using subplots() directly.
The above is the detailed content of How do `fig` and `axes` Work in Matplotlib's `subplots()` Function?. For more information, please follow other related articles on the PHP Chinese website!