YouTip LogoYouTip

Matplotlib Ref Subplots

* * * [![Image 1: Matplotlib Reference Documentation](https://example.com/images/up.gif) Matplotlib Reference Documentation](https://example.com/matplotlib/matplotlib-apiref.html) `subplots()` is the recommended way to create a Figure and a set of subplots (Axes), completing the creation of the canvas and subplots in a single call. It is the core entry function for Matplotlib's object-oriented interface. ## Function Definition ### pyplot Interface matplotlib.pyplot.subplots(nrows=1, ncols=1, *, sharex=False, sharey=False, squeeze=True, width_ratios=None, height_ratios=None, subplot_kw=None, gridspec_kw=None, **fig_kw) ### Figure Method Figure.subplots(nrows=1, ncols=1, *, sharex=False, sharey=False, squeeze=True, width_ratios=None, height_ratios=None, subplot_kw=None, gridspec_kw=None) ## Parameter Description | Parameter | Type | Description | | --- | --- | --- | | nrows | int | Number of subplot rows, default 1 | | ncols | int | Number of subplot columns, default 1 | | sharex / sharey | bool or str | Whether to share x/y axes. Can pass 'all'/'row'/'col'/'none' or boolean value | | squeeze | bool | If True, automatically removes extra dimensions for single row/column, default True | | width_ratios | list | Width ratio of each column, e.g., [1, 2] means column 2 is twice as wide as column 1 | | height_ratios | list | Height ratio of each row, e.g., [2, 1] means row 1 is twice as tall as row 2 | | subplot_kw | dict | Parameters passed to subplot creation, e.g., dict(projection='polar') creates polar subplots | | gridspec_kw | dict | Parameters passed to GridSpec, e.g., dict(hspace=0.3, wspace=0.3) sets subplot spacing | | **fig_kw | dict | Parameters passed to Figure creation, e.g., figsize=(8,6), dpi=100, layout='constrained' | > The return value of subplots() is a tuple `(fig, ax)`. When there is only one row and one column, ax is a single Axes object; for multiple rows and columns, ax is a 2D array of Axes. * * * ## Usage Examples ### Example 1: Single Subplot ## Instance import matplotlib.pyplot as plt import numpy as np # Create a single subplot (most common syntax) fig, ax = plt.subplots(figsize=(6,4), layout='constrained') x = np.linspace(0,10,100) ax.plot(x, np.sin(x)) ax.set_title('Single Subplot') ax.set_xlabel('x') ax.set_ylabel('sin(x)') ax.grid(True, alpha=0.3) plt.show() ### Example 2: One Row Multiple Columns / One Column Multiple Rows ## Instance import matplotlib.pyplot as plt import numpy as np x = np.linspace(0,10,100) # One row, three columns fig, axes = plt.subplots(1,3, figsize=(12,4), layout='constrained') # axes is a 1D array axes.plot(x, np.sin(x), color='blue') axes.set_title('sin(x)') axes.plot(x, np.cos(x), color='red') axes.set_title('cos(x)') axes.plot(x, np.tan(x), color='green') axes.set_title('tan(x)') axes.set_ylim(-5,5)# Limit y-axis range for ax in axes: ax.set_xlabel('x') ax.grid(True, alpha=0.3) fig.suptitle('Three Subplots in One Row', fontsize=14) plt.show() ### Example 3: 2x2 Grid + Width/Height Ratios ## Instance import matplotlib.pyplot as plt import numpy as np # Aspect ratio: Line1 row is taller, Line2 column is wider fig, axes = plt.subplots(2,2, figsize=(10,8), width_ratios=[1,2],# Line2Column width is 2 times that of Line1 column height_ratios=[2,1],# Line1Row height is 2 times that of Line2 row layout='constrained', sharex='col',# Each column shares the x-axis sharey='row')# Each row shares the y-axis x = np.linspace(0,10,100) # axes is a 2D array, axes[row, col] axes[0,0].plot(x, np.sin(x)) axes[0,0].set_title('sin(x)') axes[0,1].plot(x, np.cos(x),'orange') axes[0,1].set_title('cos(x)') axes[1,0].plot(x, np.sin(2*x),'green') axes[1,0].set_title('sin(2x)') axes[1,1].plot(x, np.cos(2*x),'red') axes[1,1].set_title('cos(2x)') fig.suptitle('2x2 Grid with Width/Height Ratios', fontsize=14) plt.show() ### Example 4: sharex and sharey Axis Sharing ## Instance import matplotlib.pyplot as plt import numpy as np np.random.seed(42) # Share the x-axis to facilitate time series comparison fig, axes = plt.subplots(3,1, figsize=(8,6), sharex=True,# Share the x-axis layout='constrained') t = np.linspace(0,20,200) # Three subplots share the x-axis, aligning at common time points axes.plot(t, np.sin(t),'blue') axes.set_ylabel('Signal 1') axes.grid(True, alpha=0.3) axes.plot(t, np.cos(t * 1.5),'green') axes.set_ylabel('Signal 2') axes.grid(True, alpha=0.3) axes.plot(t, np.sin(t * 0.7) + np.cos(t * 1.3),'red') axes.set_xlabel('Time (s)') axes.set_ylabel('Signal 3') axes.grid(True, alpha=0.3) fig.suptitle('Shared X-Axis: Three Time Series', fontsize=14) plt.show() ### Example 5: Polar Subplots ## Instance import matplotlib.pyplot as plt import numpy as np fig,(ax1, ax2)= plt.subplots(1,2, figsize=(10,4), subplot_kw={'projection': 'polar'},# Both are polar coordinates layout='constrained') theta = np.linspace(0,2 * np.pi,100) # Left plot: Rose curve r1 = np.abs(np.sin(3 * theta)) ax1.plot(theta, r1, color='blue', linewidth=2) ax1.set_title('Polar: Rose Curve (r=|sin(3ΞΈ)|)') # Right plot: Archimedean spiral r2 = theta / 6 ax2.plot(theta, r2, color='red', linewidth=2) ax2.set_title('Polar: Archimedean Spiral') plt.show() * * * ## FAQ ### What is the squeeze parameter for? When `squeeze=True` (default): `subplots(1,1)` returns `ax` (not ), `subplots(1,3)` returns a 1D array. When `squeeze=False`: always returns a 2D array (regardless of rows/columns), suitable for scenarios requiring unified processing. ### What is the difference between subplot_kw and gridspec_kw? `subplot_kw` is passed to each Axes creation function, such as `projection='polar'`. `gridspec_kw` is passed to the GridSpec layout manager, such as `hspace=0.4` (vertical spacing between subplots). [![Image 2: Matplotlib Reference Documentation](https://example.com/images/up.gif) Matplotlib Reference Documentation](https://example.com/matplotlib/matplotlib-apiref
← Matplotlib Ref TextMatplotlib Ref Spans Vectors β†’