Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Matplotlib subplots() Function

Matplotlib subplots() Function


Matplotlib Reference Documentation Matplotlib Reference Documentation

subplots() The recommended way to create a Figure and a set of Axes subplots; a single call completes the creation of both the canvas and the subplots.

It is the core entry function of 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

Parameters 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 the x/y axes. Can be 'all'/'row'/'col'/'none' or a boolean
squeeze bool If True, automatically removes extra dimensions for a single row/column, default True
width_ratios list Width ratio of columns, e.g. [1, 2] means the 2nd column is twice as wide as the 1st
height_ratios list Height ratio of rows, e.g. [2, 1] means the 1st row is twice as tall as the 2nd
subplot_kw dict Arguments passed to subplot creation, e.g. dict(projection='polar') creates a polar subplot
gridspec_kw dict Arguments passed to GridSpec, e.g. dict(hspace=0.3, wspace=0.3) sets the spacing between subplots
**fig_kw dict Arguments 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; with multiple rows and columns, ax is a 2D array of Axes.


Usage examples

Example 1: Single subplot

Example

import

matplotlib.

pyplot

as

plt

import

numpy

as

np

Create a single subplot (the most common form)

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 with multiple columns / one column with multiple rows

Example

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

[

0

]

.

plot

(

x

,

np.

sin

(

x

)

,

color

=

'blue'

)

axes

[

0

]

.

set_title

(

'sin(x)'

)

axes

[

1

]

.

plot

(

x

,

np.

cos

(

x

)

,

color

=

'red'

)

axes

[

1

]

.

set_title

(

'cos(x)'

)

axes

[

2

]

.

plot

(

x

,

np.

tan

(

x

)

,

color

=

'green'

)

axes

[

2

]

.

set_title

(

'tan(x)'

)

axes

[

2

]

.

set_ylim

(

5

,

5

)

 

Limit the y 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

Example

import

matplotlib.

pyplot

as

plt

import

numpy

as

np

Aspect ratio: row 1 is taller, column 2 is wider

fig

,

axes

=

plt.

subplots

(

2

,

2

,

                          figsize

=

(

10

,

8

)

,

                          width_ratios

=

[

1

,

2

]

,

 

Column 2 is twice as wide as column 1

                          height_ratios

=

[

2

,

1

]

,

 

Row 1 is twice as tall as row 2

                          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: Sharing axes with sharex and sharey

Example

import

matplotlib.

pyplot

as

plt

import

numpy

as

np

np.

random

.

seed

(

42

)

Shared x axis, convenient for comparing time series

fig

,

axes

=

plt.

subplots

(

3

,

1

,

figsize

=

(

8

,

6

)

,

                          sharex

=

True

,

           

Shared x axis

                          layout

=

'constrained'

)

t

=

np.

linspace

(

0

,

20

,

200

)

Three subplots share the x axis, aligning the same time points

axes

[

0

]

.

plot

(

t

,

np.

sin

(

t

)

,

'blue'

)

axes

[

0

]

.

set_ylabel

(

'Signal 1'

)

axes

[

0

]

.

grid

(

True

,

alpha

=

0.3

)

axes

[

1

]

.

plot

(

t

,

np.

cos

(

t *

1.5

)

,

'green'

)

axes

[

1

]

.

set_ylabel

(

'Signal 2'

)

axes

[

1

]

.

grid

(

True

,

alpha

=

0.3

)

axes

[

2

]

.

plot

(

t

,

np.

sin

(

t *

0.7

)

cos

(

t *

1.3

)

,

'red'

)

axes

[

2

]

.

set_xlabel

(

'Time (s)'

)

axes

[

2

]

.

set_ylabel

(

'Signal 3'

)

axes

[

2

]

.

grid

(

True

,

alpha

=

0.3

)

fig.

suptitle

(

'Shared X-Axis: Three Time Series'

,

fontsize

=

14

)

plt.

show

(

)

Example 5: Polar subplots

Example

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 plots

    layout

=

'constrained'

)

theta

=

np.

linspace

(

0

,

2

pi

,

100

)

Left plot: rose curve

r1

=

np.

abs

(

np.

sin

(

3

)

)

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

(

)


Common questions

What is the purpose of the squeeze parameter?

squeeze=TrueWhen (the default):subplots(1,1) Return ax(not [ax]),subplots(1,3) a 1D array is returned.

squeeze=False always returns a 2D array (regardless of the number of rows/columns), suitable for scenarios requiring uniform handling.

Difference between subplot_kw and gridspec_kw?

subplot_kw Passed to each Axes creation function, such as projection='polar'。

gridspec_kw Passed to the GridSpec layout manager, such as hspace=0.4(vertical spacing between subplots).

Matplotlib Reference Documentation Matplotlib Reference Documentation