### Navigation

- index
- modules |
- next |
- previous |
- home|
- examples|
- tutorials|
- pyplot|
- docs »
- The Matplotlib API »
- matplotlib.pyplot »

# matplotlib.pyplot.subplots

`matplotlib.pyplot.``subplots`(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None, **fig_kw)

  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, ncols : int, optional, default: 1 Number of rows/columns of the subplot grid. sharex, sharey : bool 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 visible. Similarly, when subplots have a shared y-axis along a row, only the y tick labels of the first column subplot are visible. squeeze : bool, optional, default: True If True, extra dimensions are squeezed out from the returned Axes object: if only one subplot is constructed (nrows=ncols=1), the resulting single Axes object is returned as a scalar. for Nx1 or 1xN subplots, the returned object is a 1D numpy object array of Axes objects are returned as numpy 1D arrays. for NxM, subplots with N>1 and M>1 are returned as a 2D arrays. 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. subplot_kw : dict, optional Dict with keywords passed to the `add_subplot()` call used to create each subplot. gridspec_kw : dict, 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 `figure()` call.
  Returns: | fig : `matplotlib.figure.Figure` object ax : Axes object or array of Axes objects. ax can be either a single `matplotlib.axes.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.

  See also

  `figure`, `subplot`

  Examples

  First create some toy data:

      >>> x = np.linspace(0, 2*np.pi, 400)
      >>> y = np.sin(x**2)

  Creates just a figure and only one subplot

      >>> fig, ax = plt.subplots()
      >>> ax.plot(x, y)
      >>> ax.set_title('Simple plot')

  Creates two subplots and unpacks 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)

  Creates four polar axes, and accesses them through the returned array

      >>> fig, axes = plt.subplots(2, 2, subplot_kw=dict(polar=True))
      >>> axes[0, 0].plot(x, y)
      >>> axes[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)

## Examples using `matplotlib.pyplot.subplots`

Decay

The Bayes update

Animated histogram

Image Slices Viewer

Random data

Simple Anim

Oscilloscope

Affine transform of an image

Barchart

Changing colors of lines intersecting a box

Line, Poly and RegularPoly Collection with autoscaling

Colorbar

Compound path

Date tick labels

Custom tick formatter for time series

Mmh Donuts!!!

Labeling ticks using engineering notation

Hatch-filled histograms

Configuring the font family

Using a ttf font file in matplotlib

Building histograms using Rectangles and PolyCollections

Modifying the coordinate formatter

Join styles

Legend using pre-defined labels

Artist within an artist

Circles, Wedges and Polygons

Exploring normalizations

Bezier Curve

Radar chart (aka spider or star chart)

Scatter plot with pie chart markers

Using span_where

Plots with different scales

Unicode minus

Watermark image

Text watermark

Demo Axes Hbox Divider

Demo Axes RGB

Demo Colorbar of Inset Axes

Demo Colorbar With Inset Locator

Demo New Colorbar

Inset Locator Demo

Inset Locator Demo2

Scatter Hist

Color By y-value

Styling with cycler

Colors in the default property cycle

Color Demo

Visualizing named colors

Data Browser

Figure Axes Enter Leave

Keypress Demo

Legend Picking

Looking Glass

Path Editor

Pick Event Demo

Pick Event Demo2

Poly Editor

Pong

Resampling Data

Timers

Viewlims

Frontpage 3D example

Frontpage contour example

Frontpage histogram example

Frontpage plot example

Contourf Demo

Contourf and log color scale

Clipping images with patches

Image Demo

Image Masked

Image Nonuniform

Interpolations for imshow/matshow

Pcolor Demo

pcolormesh

Quiver Simple Demo

Shading Example

Trigradient Demo

Horizontal bar chart

Broken Barh

Plotting categorical variables

Plotting the coherence of two signals

Fill plot demo

A simple plot with a custom dashed line

Line-style reference

Marker filling-styles

Filled and unfilled-marker types

Multicolored lines

Scatter Custom Symbol

Scatter Demo2

Scatter plots with a legend

Plotting with keywords

Multiprocess

Rasterization Demo

Custom hillshading in a 3D surface plot

3D wireframe plots in one direction

Nested pie charts

Basic pie chart

Agg Buffer To Array

Loglog Aspect

Axes Props

Axis Equal Demo

Broken Axis

Centered Ticklabels

Colorbar Tick Labelling Demo

Coords Demo

Coords Report

Csd Demo

Cursor Demo

Creating a colormap from a list of colors

Custom Ticker1

Dashpoint Label

Date Demo Convert

Date Demo Rrule

Date Index Formatter

Demo Annotation Box

Demo Ribbon Box

Demo Tight Layout

Dolphins

Ellipse Collection

Ellipse Demo

Errorbar Subsample

Figure legend demo

Filling the area between lines

Findobj Demo

Interp Demo

Leftventricle Bulleye

Line Collection

Log Axis

Major Minor Demo

Movie Demo

MRI

Multiple Yaxis With Spines

Psd Demo

Spectrum Representations

Spy Demos

Stackplot Demo

System Monitor

hlines and vlines

Boxplot Demo

Whats New 0.98.4 Fill Between

Fixing common date annoyances

Easily creating subplots

Fill Between and Alpha

Placing text boxes

Transparent, fancy legends

Scales

Reference for matplotlib artists

PathPatch object

Bachelor’s degrees by gender

Integral as the area under a curve

Hillshading

Topographic hillshading

Barchart Demo

Artist customization in box plots

Box plots with custom fill colors

Boxplots

Box plot vs. violin plot comparison

Boxplot drawer function

Violin plot customization

Errorbar function

Different ways of specifying error bars

Including upper and lower limits in error bars

Creating boxes from error bars using PatchCollection

Hexbin Demo

Histograms

Using histograms to plot a cumulative distribution

Demo of the histogram (hist) function with a few features

Demo of the histogram function’s different histtype settings

Demo of the histogram (hist) function with multiple data sets

Producing multiple histograms side by side

Violin plot basics

Bayesian Methods for Hackers style sheet

Dark background style sheet

FiveThirtyEight style sheet

ggplot style sheet

Grayscale style sheet

Style sheets reference

Different scales on the same axes

Creating adjacent subplots

Subplot Toolbar

Subplots Demo

Using accented text in matplotlib

Annotating Plots

Legend Demo

Rendering math equation using TeX

Default text rotation demonstration

Automatically setting tick labels

Tick formatting using the ScalarFromatter

Spines

Custom spine bounds

Dropped spines

Annotation with units

Artist tests

Bar demo with units

Group barchart with units

Unit handling

Lineprops Dialog GTK

Pylab With GTK

SVG Tooltip

Anchored Box01

Anchored Box02

Anchored Box03

Anchored Box04

Annotate Simple01

Annotate Simple02

Annotate Simple03

Annotate Simple04

Annotate Simple Coord01

Annotate Simple Coord02

Annotate Simple Coord03

Annotate Text Arrow

Colormap Normalizations

Colormap Normalizations Bounds

Colormap Normalizations Custom

Colormap Normalizations Lognorm

Colormap Normalizations Power

Colormap Normalizations Symlognorm

Connect Simple01

Custom Boxstyle01

Custom Boxstyle02

Simple Legend02

Buttons

Check Buttons

Lasso Selector Demo

Polygon Selector Demo

Radio Buttons

Rectangle Selector

Slider Demo

Textbox

The Lifecycle of a Plot

Sample plots in Matplotlib

Usage Guide

Artist tutorial

Tight Layout guide

Customized Colorbars Tutorial

Colormap Normalization

Colormaps in Matplotlib

Specifying Colors