matplotlib.pyplot.subplots#

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)[source]#

Create a figure and a set of subplots.

This utility wrapper makes it convenient to create common layouts of subplots, including the enclosing figure object, in a single call.

Parameters:
nrows, ncolsint, default: 1

Number of rows/columns of the subplot grid.

sharex, shareybool or {'none', 'all', 'row', 'col'}, default: False

Controls sharing of properties among x (sharex) or y (sharey) axes:

  • True or 'all': x- or y-axis will be shared among all subplots.

  • False or 'none': each subplot x- or y-axis will be independent.

  • 'row': each subplot row will share an x- or y-axis.

  • 'col': each subplot column will share an x- or y-axis.

When subplots have a shared x-axis along a column, only the x tick labels of the bottom subplot are created. Similarly, when subplots have a shared y-axis along a row, only the y tick labels of the first column subplot are created. To later turn other subplots' ticklabels on, use tick_params.

When subplots have a shared axis that has units, calling Axis.set_units will update each axis with the new units.

Note that it is not possible to unshare axes.

squeezebool, default: True
  • If True, extra dimensions are squeezed out from the returned array of Axes:

    • if only one subplot is constructed (nrows=ncols=1), the resulting single Axes object is returned as a scalar.

    • for Nx1 or 1xM subplots, the returned object is a 1D numpy object array of Axes objects.

    • for NxM, subplots with N>1 and M>1 are returned as a 2D array.

  • If False, no squeezing at all is done: the returned Axes object is always a 2D array containing Axes instances, even if it ends up being 1x1.

width_ratiosarray-like of length ncols, optional

Defines the relative widths of the columns. Each column gets a relative width of width_ratios[i] / sum(width_ratios). If not given, all columns will have the same width. Equivalent to gridspec_kw={'width_ratios': [...]}.

height_ratiosarray-like of length nrows, optional

Defines the relative heights of the rows. Each row gets a relative height of height_ratios[i] / sum(height_ratios). If not given, all rows will have the same height. Convenience for gridspec_kw={'height_ratios': [...]}.

subplot_kwdict, optional

Dict with keywords passed to the add_subplot call used to create each subplot.

gridspec_kwdict, optional

Dict with keywords passed to the GridSpec constructor used to create the grid the subplots are placed on.

**fig_kw

All additional keyword arguments are passed to the pyplot.figure call.

Returns:
figFigure
axAxes or array of Axes

ax can be either a single Axes object, or an array of Axes objects if more than one subplot was created. The dimensions of the resulting array can be controlled with the squeeze keyword, see above.

Typical idioms for handling the return value are:

# using the variable ax for single a Axes
fig, ax = plt.subplots()

# using the variable axs for multiple Axes
fig, axs = plt.subplots(2, 2)

# using tuple unpacking for multiple Axes
fig, (ax1, ax2) = plt.subplots(1, 2)
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)

The names ax and pluralized axs are preferred over axes because for the latter it's not clear if it refers to a single Axes instance or a collection of these.

Examples

# First create some toy data:
x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)

# Create just a figure and only one subplot
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_title('Simple plot')

# Create two subplots and unpack the output array immediately
f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
ax1.plot(x, y)
ax1.set_title('Sharing Y axis')
ax2.scatter(x, y)

# Create four polar Axes and access them through the returned array
fig, axs = plt.subplots(2, 2, subplot_kw=dict(projection="polar"))
axs[0, 0].plot(x, y)
axs[1, 1].scatter(x, y)

# Share a X axis with each column of subplots
plt.subplots(2, 2, sharex='col')

# Share a Y axis with each row of subplots
plt.subplots(2, 2, sharey='row')

# Share both X and Y axes with all subplots
plt.subplots(2, 2, sharex='all', sharey='all')

# Note that this is the same as
plt.subplots(2, 2, sharex=True, sharey=True)

# Create figure number 10 with a single subplot
# and clears it if it already exists.
fig, ax = plt.subplots(num=10, clear=True)

Examples using matplotlib.pyplot.subplots#

Bar chart with individual bar colors

Bar chart with individual bar colors

Bar chart with labels

Bar chart with labels

Stacked bar chart

Stacked bar chart

Grouped bar chart with labels

Grouped bar chart with labels

Horizontal bar chart

Horizontal bar chart

Broken Barh

Broken Barh

Plotting categorical variables

Plotting categorical variables

Plotting the coherence of two signals

Plotting the coherence of two signals

Cross spectral density (CSD)

Cross spectral density (CSD)

Curve with error band

Curve with error band

Errorbar subsampling

Errorbar subsampling

Eventplot demo

Eventplot demo

Filled polygon

Filled polygon

fill_between with transparency

fill_between with transparency

Fill the area between two lines

Fill the area between two lines

Fill the area between two vertical lines

Fill the area between two vertical lines

Bar chart with gradients

Bar chart with gradients

Hat graph

Hat graph

Discrete distribution as horizontal bar chart

Discrete distribution as horizontal bar chart

Dashed line style configuration

Dashed line style configuration

Lines with a ticked patheffect

Lines with a ticked patheffect

Linestyles

Linestyles

Marker reference

Marker reference

Markevery Demo

Markevery Demo

Multicolored lines

Multicolored lines

Mapping marker properties to multivariate data

Mapping marker properties to multivariate data

Power spectral density (PSD)

Power spectral density (PSD)

Scatter Demo2

Scatter Demo2

Marker examples

Marker examples

Scatter plot with a legend

Scatter plot with a legend

Line plot

Line plot

Shade regions defined by a logical mask using fill_between

Shade regions defined by a logical mask using fill_between

Stackplots and streamgraphs

Stackplots and streamgraphs

Stairs Demo

Stairs Demo

Timeline with lines, dates, and text

Timeline with lines, dates, and text

hlines and vlines

hlines and vlines

Cross- and auto-correlation

Cross- and auto-correlation

Affine transform of an image

Affine transform of an image

Wind barbs

Wind barbs

Interactive adjustment of colormap range

Interactive adjustment of colormap range

Colormap normalizations

Colormap normalizations

Colormap normalizations SymLogNorm

Colormap normalizations SymLogNorm

Contour corner mask

Contour corner mask

Contour Demo

Contour Demo

Contour image

Contour image

Contour Label Demo

Contour Label Demo

Contourf demo

Contourf demo

Contourf hatching

Contourf hatching

Contourf and log color scale

Contourf and log color scale

Contouring the solution space of optimizations

Contouring the solution space of optimizations

BboxImage Demo

BboxImage Demo

Annotated heatmap

Annotated heatmap

Image resampling

Image resampling

Clipping images with patches

Clipping images with patches

Many ways to plot images

Many ways to plot images

Image with masked values

Image with masked values

Image nonuniform

Image nonuniform

Blend transparency with color in 2D images

Blend transparency with color in 2D images

Modifying the coordinate formatter

Modifying the coordinate formatter

Interpolations for imshow

Interpolations for imshow

Contour plot of irregularly spaced data

Contour plot of irregularly spaced data

Multiple images with one colorbar

Multiple images with one colorbar

pcolor images

pcolor images

pcolormesh grids and shading

pcolormesh grids and shading

pcolormesh

pcolormesh

Streamplot

Streamplot

QuadMesh Demo

QuadMesh Demo

Advanced quiver and quiverkey functions

Advanced quiver and quiverkey functions

Quiver Simple Demo

Quiver Simple Demo

Shading example

Shading example

Spectrogram

Spectrogram

Spy Demos

Spy Demos

Tricontour Demo

Tricontour Demo

Tricontour Smooth Delaunay

Tricontour Smooth Delaunay

Tricontour Smooth User

Tricontour Smooth User

Trigradient Demo

Trigradient Demo

Triinterp Demo

Triinterp Demo

Tripcolor Demo

Tripcolor Demo

Triplot Demo

Triplot Demo

Watermark image

Watermark image

Align labels and titles

Align labels and titles

Programmatically control subplot adjustment

Programmatically control subplot adjustment

Axes box aspect

Axes box aspect

Axes Demo

Axes Demo

Controlling view limits using margins and sticky_edges

Controlling view limits using margins and sticky_edges

Axes properties

Axes properties

Draw regions that span an Axes

Draw regions that span an Axes

Equal axis aspect ratio

Equal axis aspect ratio

Axis label position

Axis label position

Broken axis

Broken axis

Resize Axes with constrained layout

Resize Axes with constrained layout

Resize Axes with tight layout

Resize Axes with tight layout

Different scales on the same Axes

Different scales on the same Axes

Figure size in different units

Figure size in different units

Figure labels: suptitle, supxlabel, supylabel

Figure labels: suptitle, supxlabel, supylabel

Adjacent subplots

Adjacent subplots

Combine two subplots using subplots and GridSpec

Combine two subplots using subplots and GridSpec

Inverted axis

Inverted axis

Secondary Axis

Secondary Axis

Figure subfigures

Figure subfigures

Multiple subplots

Multiple subplots

Create multiple subplots using plt.subplots

Create multiple subplots using plt.subplots

Plots with different scales

Plots with different scales

Zoom region inset Axes

Zoom region inset Axes

Artist customization in box plots

Artist customization in box plots

Box plots with custom fill colors

Box plots with custom fill colors

Boxplots

Boxplots

Box plot vs. violin plot comparison

Box plot vs. violin plot comparison

Separate calculation and plotting of boxplots

Separate calculation and plotting of boxplots

Plot a confidence ellipse of a two-dimensional dataset

Plot a confidence ellipse of a two-dimensional dataset

Violin plot customization

Violin plot customization

Errorbar function

Errorbar function

Different ways of specifying error bars

Different ways of specifying error bars

Including upper and lower limits in error bars

Including upper and lower limits in error bars

Create boxes from error bars using PatchCollection

Create boxes from error bars using PatchCollection

Hexagonal binned plot

Hexagonal binned plot

Histograms

Histograms

Bihistogram

Bihistogram

Demo of the histogram function's different histtype settings

Demo of the histogram function's different histtype settings

The histogram (hist) function with multiple data sets

The histogram (hist) function with multiple data sets

Histogram bins, density, and weight

Histogram bins, density, and weight

Multiple histograms side by side

Multiple histograms side by side

Time Series Histogram

Time Series Histogram

Violin plot basics

Violin plot basics

Pie charts

Pie charts

Bar of pie

Bar of pie

Nested pie charts

Nested pie charts

A pie and a donut with labels

A pie and a donut with labels

Polar plot

Polar plot

Accented text

Accented text

Align y-labels

Align y-labels

Scale invariant angle label

Scale invariant angle label

Angle annotations on bracket arrows

Angle annotations on bracket arrows

Annotate transform

Annotate transform

Annotating a plot

Annotating a plot

Annotate plots

Annotate plots

Compose custom legends

Compose custom legends

Date tick labels

Date tick labels

AnnotationBbox demo

AnnotationBbox demo

Using a text as a Path

Using a text as a Path

Format ticks using engineering notation

Format ticks using engineering notation

Figure legend demo

Figure legend demo

Configure the font family

Configure the font family

Using ttf font files

Using ttf font files

Font table

Font table

Legend using pre-defined labels

Legend using pre-defined labels

Legend Demo

Legend Demo

Artist within an artist

Artist within an artist

Mathtext

Mathtext

Math fontfamily

Math fontfamily

Multiline

Multiline

Placing text boxes

Placing text boxes

Render math equations using TeX

Render math equations using TeX

Text alignment

Text alignment

Text rotation angle in data coordinates

Text rotation angle in data coordinates

Title positioning

Title positioning

Text watermark

Text watermark

Color Demo

Color Demo

Color by y-value

Color by y-value

Colors in the default property cycle

Colors in the default property cycle

Colorbar

Colorbar

Colormap reference

Colormap reference

Create a colormap from a list of colors

Create a colormap from a list of colors

Selecting individual colors from a colormap

Selecting individual colors from a colormap

List of named colors

List of named colors

Ways to set a color's alpha value

Ways to set a color's alpha value

Arrow guide

Arrow guide

Line, Poly and RegularPoly Collection with autoscaling

Line, Poly and RegularPoly Collection with autoscaling

Compound path

Compound path

Dolphins

Dolphins

Mmh Donuts!!!

Mmh Donuts!!!

Ellipse with orientation arrow demo

Ellipse with orientation arrow demo

Ellipse Collection

Ellipse Collection

Ellipse Demo

Ellipse Demo

Drawing fancy boxes

Drawing fancy boxes

Hatch style reference

Hatch style reference

Plot multiple lines using a LineCollection

Plot multiple lines using a LineCollection

Circles, Wedges and Polygons

Circles, Wedges and Polygons

PathPatch object

PathPatch object

Bezier curve

Bezier curve

Bayesian Methods for Hackers style sheet

Bayesian Methods for Hackers style sheet

Dark background style sheet

Dark background style sheet

FiveThirtyEight style sheet

FiveThirtyEight style sheet

ggplot style sheet

ggplot style sheet

Grayscale style sheet

Grayscale style sheet

Petroff10 style sheet

Petroff10 style sheet

Style sheets reference

Style sheets reference

Anchored Direction Arrow

Anchored Direction Arrow

HBoxDivider and VBoxDivider demo

HBoxDivider and VBoxDivider demo

Show RGB channels using RGBAxes

Show RGB channels using RGBAxes

Colorbar with AxesDivider

Colorbar with AxesDivider

Control the position and size of a colorbar with Inset Axes

Control the position and size of a colorbar with Inset Axes

Inset locator demo

Inset locator demo

Inset locator demo 2

Inset locator demo 2

Align histogram to scatter plot using locatable Axes

Align histogram to scatter plot using locatable Axes

Simple Anchored Artists

Simple Anchored Artists

Integral as the area under a curve

Integral as the area under a curve

Stock prices over 32 years

Stock prices over 32 years

Decay

Decay

Animated histogram

Animated histogram

pyplot animation

pyplot animation

The Bayes update

The Bayes update

Animated image using a precomputed list of images

Animated image using a precomputed list of images

Multiple Axes animation

Multiple Axes animation

Pause and resume an animation

Pause and resume an animation

Animated line plot

Animated line plot

Animated scatter saved as GIF

Animated scatter saved as GIF

Oscilloscope

Oscilloscope

Mouse move and click events

Mouse move and click events

Cross-hair cursor

Cross-hair cursor

Data browser

Data browser

Figure/Axes enter and leave events

Figure/Axes enter and leave events

Scroll event

Scroll event

Keypress event

Keypress event

Legend picking

Legend picking

Looking glass

Looking glass

Path editor

Path editor

Pick event demo

Pick event demo

Pick event demo 2

Pick event demo 2

Polygon editor

Polygon editor

Pong

Pong

Resampling Data

Resampling Data

Timers

Timers

Trifinder Event Demo

Trifinder Event Demo

Viewlims

Viewlims

Zoom modifies other Axes

Zoom modifies other Axes

Anchored Artists

Anchored Artists

Identify whether artists intersect

Identify whether artists intersect

Manual Contour

Manual Contour

Coords Report

Coords Report

Custom projection

Custom projection

AGG filter

AGG filter

Ribbon box

Ribbon box

Add lines directly to a figure

Add lines directly to a figure

Findobj Demo

Findobj Demo

Building histograms using Rectangles and PolyCollections

Building histograms using Rectangles and PolyCollections

Plotting with keywords

Plotting with keywords

Multiprocessing

Multiprocessing

Packed-bubble chart

Packed-bubble chart

Patheffect Demo

Patheffect Demo

Rasterization for vector graphics

Rasterization for vector graphics

TickedStroke patheffect

TickedStroke patheffect

Zorder Demo

Zorder Demo

Clip the data to the axes view limits

Clip the data to the axes view limits

Custom hillshading in a 3D surface plot

Custom hillshading in a 3D surface plot

3D plot projection types

3D plot projection types

3D stem

3D stem

3D surface (colormap)

3D surface (colormap)

3D wireframe plots in one direction

3D wireframe plots in one direction

Loglog aspect

Loglog aspect

Log Bar

Log Bar

Log Demo

Log Demo

Logit Demo

Logit Demo

Exploring normalizations

Exploring normalizations

Scales

Scales

Log Axis

Log Axis

Symlog Demo

Symlog Demo

Hillshading

Hillshading

Anscombe's quartet

Anscombe's quartet

Ishikawa Diagram

Ishikawa Diagram

Radar chart (aka spider or star chart)

Radar chart (aka spider or star chart)

Topographic hillshading

Topographic hillshading

Spines

Spines

Dropped spines

Dropped spines

Multiple y-axis with Spines

Multiple y-axis with Spines

Centered spines with arrows

Centered spines with arrows

Automatically setting tick positions

Automatically setting tick positions

Center labels between ticks

Center labels between ticks

Colorbar Tick Labelling

Colorbar Tick Labelling

Custom Ticker

Custom Ticker

Format date ticks using ConciseDateFormatter

Format date ticks using ConciseDateFormatter

Date Demo Convert

Date Demo Convert

Placing date ticks using recurrence rules

Placing date ticks using recurrence rules

Date tick locators and formatters

Date tick locators and formatters

Custom tick formatter for time series

Custom tick formatter for time series

Date precision and epochs

Date precision and epochs

Dollar ticks

Dollar ticks

SI prefixed offsets and natural order of magnitudes

SI prefixed offsets and natural order of magnitudes

Major and minor ticks

Major and minor ticks

Multilevel (nested) ticks

Multilevel (nested) ticks

The default tick formatter

The default tick formatter

Tick locators

Tick locators

Set default y-axis tick labels on the right

Set default y-axis tick labels on the right

Setting tick labels from a list of values

Setting tick labels from a list of values

Move x-axis tick labels to the top

Move x-axis tick labels to the top

Rotated tick labels

Rotated tick labels

Fixing too many ticks

Fixing too many ticks

Annotation with units

Annotation with units

Artist tests

Artist tests

Bar demo with units

Bar demo with units

Group barchart with units

Group barchart with units

Evans test

Evans test

Radian ticks

Radian ticks

Inches and centimeters

Inches and centimeters

Unit handling

Unit handling

pyplot with GTK3

pyplot with GTK3

pyplot with GTK4

pyplot with GTK4

SVG Tooltip

SVG Tooltip

Annotated cursor

Annotated cursor

Buttons

Buttons

Check buttons

Check buttons

Cursor

Cursor

Lasso Selector

Lasso Selector

Mouse Cursor

Mouse Cursor

Multicursor

Multicursor

Select indices from a collection using polygon selector

Select indices from a collection using polygon selector

Polygon Selector

Polygon Selector

Image scaling using a RangeSlider

Image scaling using a RangeSlider

Slider

Slider

Snap sliders to discrete values

Snap sliders to discrete values

Span Selector

Span Selector

Textbox

Textbox

Simple Legend02

Simple Legend02

The Lifecycle of a Plot

The Lifecycle of a Plot

Artist tutorial

Artist tutorial

plot(x, y)

plot(x, y)

scatter(x, y)

scatter(x, y)

bar(x, height)

bar(x, height)

stem(x, y)

stem(x, y)

fill_between(x, y1, y2)

fill_between(x, y1, y2)

stackplot(x, y)

stackplot(x, y)

stairs(values)

stairs(values)

hist(x)

hist(x)

boxplot(X)

boxplot(X)

errorbar(x, y, yerr, xerr)

errorbar(x, y, yerr, xerr)

violinplot(D)

violinplot(D)

eventplot(D)

eventplot(D)

hist2d(x, y)

hist2d(x, y)

hexbin(x, y, C)

hexbin(x, y, C)

pie(x)

pie(x)

ecdf(x)

ecdf(x)

imshow(Z)

imshow(Z)

pcolormesh(X, Y, Z)

pcolormesh(X, Y, Z)

contour(X, Y, Z)

contour(X, Y, Z)

contourf(X, Y, Z)

contourf(X, Y, Z)

barbs(X, Y, U, V)

barbs(X, Y, U, V)

quiver(X, Y, U, V)

quiver(X, Y, U, V)

streamplot(X, Y, U, V)

streamplot(X, Y, U, V)

tricontour(x, y, z)

tricontour(x, y, z)

tricontourf(x, y, z)

tricontourf(x, y, z)

tripcolor(x, y, z)

tripcolor(x, y, z)

triplot(x, y)

triplot(x, y)

bar3d(x, y, z, dx, dy, dz)

bar3d(x, y, z, dx, dy, dz)

fill_between(x1, y1, z1, x2, y2, z2)

fill_between(x1, y1, z1, x2, y2, z2)

plot(xs, ys, zs)

plot(xs, ys, zs)

quiver(X, Y, Z, U, V, W)

quiver(X, Y, Z, U, V, W)

scatter(xs, ys, zs)

scatter(xs, ys, zs)

stem(x, y, z)

stem(x, y, z)

plot_surface(X, Y, Z)

plot_surface(X, Y, Z)

plot_trisurf(x, y, z)

plot_trisurf(x, y, z)

voxels([x, y, z], filled)

voxels([x, y, z], filled)

plot_wireframe(X, Y, Z)

plot_wireframe(X, Y, Z)

Quick start guide

Quick start guide

Animations using Matplotlib

Animations using Matplotlib

Faster rendering by using blitting

Faster rendering by using blitting

Styling with cycler

Styling with cycler

Path Tutorial

Path Tutorial

Transformations Tutorial

Transformations Tutorial

Legend guide

Legend guide

Constrained layout guide

Constrained layout guide

Tight layout guide

Tight layout guide

Arranging multiple Axes in a Figure

Arranging multiple Axes in a Figure

Autoscaling Axis

Autoscaling Axis

Axis scales

Axis scales

Axis ticks

Axis ticks

Plotting dates and strings

Plotting dates and strings

Placing colorbars

Placing colorbars

Specifying colors

Specifying colors

Customized Colorbars Tutorial

Customized Colorbars Tutorial

Creating Colormaps in Matplotlib

Creating Colormaps in Matplotlib

Colormap normalization

Colormap normalization

Choosing Colormaps in Matplotlib

Choosing Colormaps in Matplotlib

Text in Matplotlib

Text in Matplotlib

Annotations

Annotations