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 color demo

Bar color demo

Bar Label Demo

Bar Label Demo

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 and Alpha

Fill Between and Alpha

Filling the area between lines

Filling the area between lines

Fill Betweenx Demo

Fill Betweenx Demo

Hatch-filled histograms

Hatch-filled histograms

Bar chart with gradients

Bar chart with gradients

Hat graph

Hat graph

Discrete distribution as horizontal bar chart

Discrete distribution as horizontal bar chart

Customizing dashed line styles

Customizing dashed line styles

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 plots with a legend

Scatter plots with a legend

Simple Plot

Simple 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

Creating a timeline with lines, dates, and text

Creating a 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

Creating annotated heatmaps

Creating annotated heatmaps

Image antialiasing

Image antialiasing

Clipping images with patches

Clipping images with patches

Many ways to plot images

Many ways to plot images

Image Masked

Image Masked

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

Aligning Labels and Titles

Aligning Labels and Titles

Programmatically controlling subplot adjustment

Programmatically controlling 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 Props

Axes Props

axhspan Demo

axhspan Demo

Equal axis aspect ratio

Equal axis aspect ratio

Axis Label Position

Axis Label Position

Broken Axis

Broken Axis

Resizing Axes with constrained layout

Resizing Axes with constrained layout

Resizing Axes with tight layout

Resizing 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

Creating adjacent subplots

Creating adjacent subplots

Combining two subplots using subplots and GridSpec

Combining two subplots using subplots and GridSpec

Inverted axis

Inverted axis

Secondary Axis

Secondary Axis

Figure subfigures

Figure subfigures

Multiple subplots

Multiple subplots

Creating multiple subplots using plt.subplots

Creating multiple subplots using plt.subplots

Plots with different scales

Plots with different scales

Zoom region inset Axes

Zoom region inset Axes

Percentiles as horizontal bar chart

Percentiles as horizontal bar chart

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

Creating boxes from error bars using PatchCollection

Creating 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

Producing multiple histograms side by side

Producing 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

Labeling a pie and a donut

Labeling a pie and a donut

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

Annotating Plots

Annotating Plots

Composing Custom Legends

Composing Custom Legends

Date tick labels

Date tick labels

AnnotationBbox demo

AnnotationBbox demo

Using a text as a Path

Using a text as a Path

Labeling ticks using engineering notation

Labeling ticks using engineering notation

Figure legend demo

Figure legend demo

Configuring the font family

Configuring 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

Rendering math equations using TeX

Rendering math equations using TeX

Text alignment

Text alignment

Text Rotation Relative To Line

Text Rotation Relative To Line

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

Creating a colormap from a list of colors

Creating 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

Plotting multiple lines with a LineCollection

Plotting multiple lines with 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

Style sheets reference

Style sheets reference

Anchored Direction Arrow

Anchored Direction Arrow

HBoxDivider and VBoxDivider demo

HBoxDivider and VBoxDivider demo

Showing RGB channels using RGBAxes

Showing RGB channels using RGBAxes

Colorbar with AxesDivider

Colorbar with AxesDivider

Controlling the position and size of colorbars with Inset Axes

Controlling the position and size of colorbars with Inset Axes

Inset locator demo

Inset locator demo

Inset locator demo 2

Inset locator demo 2

Scatter Histogram (Locatable Axes)

Scatter Histogram (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

Pausing and Resuming an Animation

Pausing and Resuming 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

Poly Editor

Poly Editor

Pong

Pong

Resampling Data

Resampling Data

Timers

Timers

Trifinder Event Demo

Trifinder Event Demo

Viewlims

Viewlims

Zoom Window

Zoom Window

Anchored Artists

Anchored Artists

Changing colors of lines intersecting a box

Changing colors of lines intersecting a box

Manual Contour

Manual Contour

Coords Report

Coords Report

Custom projection

Custom projection

AGG filter

AGG filter

Ribbon Box

Ribbon Box

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

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

Centering labels between ticks

Centering labels between ticks

Colorbar Tick Labelling

Colorbar Tick Labelling

Custom Ticker

Custom Ticker

Formatting date ticks using ConciseDateFormatter

Formatting 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

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

Rotating custom tick labels

Rotating custom 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

Thresholding an Image with RangeSlider

Thresholding an Image with RangeSlider

Slider

Slider

Snapping Sliders to Discrete Values

Snapping Sliders to Discrete Values

Span Selector

Span Selector

Textbox

Textbox

Annotate Explain

Annotate Explain

Annotate Text Arrow

Annotate Text Arrow

Connection styles for annotations

Connection styles for annotations

Custom box styles

Custom box styles

PGF fonts

PGF fonts

PGF preamble

PGF preamble

PGF texsystem

PGF texsystem

Simple Annotate01

Simple Annotate01

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)

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