Matplotlib - Subplots() Function
Matplotlib - Using the subplots() Function
Section titled “Matplotlib - Using the subplots() Function”The matplotlib.pyplot.subplots() function is a highly convenient utility for creating a Figure and a set of subplots (arranged in a grid) simultaneously. It is the recommended approach for creating multiple plots in the object-oriented style.
fig, axes = plt.subplots(nrows=1, ncols=1, **kwargs)Arguments:
nrows,ncols: Integers specifying the number of rows and columns in the subplot grid. Defaults to 1.sharex,sharey: Boolean or string (‘all’, ‘row’, ‘col’). IfTrueor'all', subplots will share the same x-axis or y-axis (ticks, limits, scale).'row'shares within rows,'col'shares within columns. This is very useful for linked plots.figsize: Tuple(width, height)in inches for the figure.subplot_kw: Dictionary of keywords passed to theadd_subplot()call for each subplot (e.g.,{'projection': '3d'}).gridspec_kw: Dictionary of keywords passed to theGridSpecconstructor (e.g.,{'hspace': 0.1, 'wspace': 0.1}) for finer control over spacing.- …and other figure keywords.
Return Values:
fig: The top-levelmatplotlib.figure.Figureobject.axes: AnAxesobject or an array ofAxesobjects. - Ifnrows=1andncols=1,axesis a singleAxesobject. - Ifnrows > 1orncols > 1,axesis a NumPy array ofAxesobjects. You access individual axes using standard array indexing (e.g.,axes[0],axes[1, 2]).
Example: Creating a 2x2 grid and plotting different functions.
import matplotlib.pyplot as pltimport numpy as np
x = np.arange(1, 5)
# Create a 2x2 grid of subplots# Share the y-axis among plots in the same rowfig, axes = plt.subplots(nrows=2, ncols=2, figsize=(8, 7), sharey='row')
# --- Plot on each Axes object ---
# Top-left plot (axes[0, 0])axes[0, 0].plot(x, x*x, color='blue', marker='o')axes[0, 0].set_title('Square ($x^2$)')axes[0, 0].set_ylabel('Value') # Y-label only needed once per row due to shareyaxes[0, 0].grid(True)
# Top-right plot (axes[0, 1])axes[0, 1].plot(x, np.sqrt(x), color='red', marker='s')axes[0, 1].set_title('Square Root ($\sqrt{x}$)')axes[0, 1].grid(True)
# Bottom-left plot (axes[1, 0])axes[1, 0].plot(x, np.exp(x), color='green', marker='^')axes[1, 0].set_title('Exponential ($e^x$)')axes[1, 0].set_xlabel('Input x') # X-label for bottom rowaxes[1, 0].set_ylabel('Value')axes[1, 0].grid(True)
# Bottom-right plot (axes[1, 1])axes[1, 1].plot(x, np.log10(x), color='purple', marker='d')axes[1, 1].set_title('Logarithm ($\log_{10}(x)$)')axes[1, 1].set_xlabel('Input x')axes[1, 1].grid(True)
# --- Overall Figure Adjustments ---
# Add a centered title for the entire figurefig.suptitle('Demonstrating plt.subplots()', fontsize=16)
# Adjust layout to prevent titles/labels overlappingplt.tight_layout(rect=[0, 0, 1, 0.96]) # rect adjusts for suptitle
plt.show()This example demonstrates creating a 2x2 grid, accessing each Axes using array notation (axes[row, col]), plotting different data on each, setting individual titles, and using shared axes (sharey='row') so that the y-axis limits and ticks are linked for plots in the same row. plt.tight_layout() is often essential when working with multiple subplots to ensure labels and titles don’t overlap.