Skip to content
LearnPY
Matplotlibfunction reference

plt.subplots

Create a figure and one or more axes in one call.

Signature

plt.subplots(nrows=1, ncols=1, figsize=None, sharex=False, sharey=False)

What it does

plt.subplots is the recommended starting point for most figures. It returns a Figure and an Axes object, or an array of axes when you request more than one panel. Explicit figure and axes objects make it easier to control layout and reuse code.

Parameters

nrowsint, optionaloptional
Number of rows of subplots.
ncolsint, optionaloptional
Number of columns of subplots.
figsizetuple of numbers, optionaloptional
Figure width and height in inches.
sharexbool, optionaloptional
Share the x-axis across panels.

Returns

tuple containing a Figure and an Axes or ndarray of Axes

Example

pythonplt.subplots example
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(6, 3))
ax.plot([1, 2, 3], [2, 4, 3])
ax.set(title="A small line chart", xlabel="step", ylabel="value")
fig.savefig("chart.png", bbox_inches="tight")

Watch out for

  • With multiple panels, indexing can return a 1D or 2D array; inspect the shape before assuming ax[0, 1].
  • Use the object-oriented fig, ax API instead of relying on the global pyplot state in reusable code.