How to Use fig.add_subplot in Matplotlib for Plotting
Use
fig.add_subplot to add a subplot to a matplotlib figure by specifying the number of rows, columns, and the index of the subplot. It returns an Axes object where you can plot your data. This method helps organize multiple plots in one figure.Syntax
The fig.add_subplot method has this basic syntax:
fig.add_subplot(nrows, ncols, index)
Where:
- nrows: Number of rows in the grid of subplots.
- ncols: Number of columns in the grid of subplots.
- index: Position of the subplot in the grid (starts at 1, goes left to right, top to bottom).
This creates a subplot in the specified position and returns an Axes object to plot on.
python
fig.add_subplot(nrows, ncols, index)
Example
This example creates a figure with 2 rows and 2 columns of subplots, then plots simple lines on each subplot.
python
import matplotlib.pyplot as plt fig = plt.figure() # Add first subplot in position 1 (top-left) ax1 = fig.add_subplot(2, 2, 1) ax1.plot([1, 2, 3], [1, 4, 9]) ax1.set_title('Plot 1') # Add second subplot in position 2 (top-right) ax2 = fig.add_subplot(2, 2, 2) ax2.plot([1, 2, 3], [2, 3, 4]) ax2.set_title('Plot 2') # Add third subplot in position 3 (bottom-left) ax3 = fig.add_subplot(2, 2, 3) ax3.plot([1, 2, 3], [5, 6, 7]) ax3.set_title('Plot 3') # Add fourth subplot in position 4 (bottom-right) ax4 = fig.add_subplot(2, 2, 4) ax4.plot([1, 2, 3], [7, 8, 9]) ax4.set_title('Plot 4') plt.tight_layout() plt.show()
Output
A window with a figure showing 4 subplots arranged in 2 rows and 2 columns, each with a simple line plot and a title: Plot 1, Plot 2, Plot 3, Plot 4.
Common Pitfalls
Common mistakes when using fig.add_subplot include:
- Using an
indexvalue outside the valid range (less than 1 or greater thannrows * ncols). - Confusing the
indexwith zero-based indexing (it starts at 1). - Not calling
plt.tight_layout()to avoid overlapping labels and titles.
Example of wrong and right usage:
python
import matplotlib.pyplot as plt fig = plt.figure() # Wrong: index 0 (invalid) # ax = fig.add_subplot(2, 2, 0) # This will raise an error # Right: index starts at 1 ax = fig.add_subplot(2, 2, 1) ax.plot([1, 2, 3], [1, 4, 9]) ax.set_title('Correct subplot') plt.tight_layout() plt.show()
Output
A figure window with one subplot showing a line plot titled 'Correct subplot'.
Quick Reference
Remember these tips when using fig.add_subplot:
- The
indexcounts left to right, top to bottom, starting at 1. - Use
plt.tight_layout()to improve spacing. - You can also use a 3-digit integer for
add_subplot, likefig.add_subplot(221)for 2 rows, 2 columns, position 1.
Key Takeaways
Use fig.add_subplot(nrows, ncols, index) to create subplots in a figure grid.
The index starts at 1 and counts left to right, top to bottom.
Always call plt.tight_layout() to avoid overlapping plot elements.
You get an Axes object from add_subplot to plot your data.
Avoid using index values outside the valid range to prevent errors.