matplotlib.pyplot.subplots   matplotlib.pyplot.subplots(nrows=1, ncols=1, *, sharex=False, sharey=False, squeeze=True, 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 set_units will update each axis with the new units.  
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.   
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.Axes 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.      See also  pyplot.figure
pyplot.subplot
pyplot.axes
Figure.subplots
Figure.add_subplot
  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 Label Demo   

   Stacked bar chart   

   Grouped bar chart with labels   

   Horizontal bar chart   

   Broken Barh   

   Plotting categorical variables   

   Plotting the coherence of two signals   

   CSD Demo   

   Curve with error band   

   Errorbar subsampling   

   Eventplot Demo   

   Filled polygon   

   Fill Between and Alpha   

   Filling the area between lines   

   Fill Betweenx Demo   

   Hatch-filled histograms   

   Bar chart with gradients   

   Hat graph   

   Discrete distribution as horizontal bar chart   

   Customizing dashed line styles   

   Lines with a ticked patheffect   

   Marker reference   

   Multicolored lines   

   Psd Demo   

   Scatter Custom Symbol   

   Scatter Demo2   

   Scatter plot with pie chart markers   

   Marker examples   

   Scatter plots with a legend   

   Simple Plot   

   Using span_where   

   Spectrum Representations   

   Stackplots and streamgraphs   

   Stairs Demo   

   Creating a timeline with lines, dates, and text   

   hlines and vlines   

   Cross- and Auto-Correlation Demo   

   Affine transform of an image   

   Wind Barbs   

   Contour Corner Mask   

   Contour Demo   

   Contour Image   

   Contour Label Demo   

   Contourf Demo   

   Contourf Hatching   

   Contourf and log color scale   

   Contouring the solution space of optimizations   

   BboxImage Demo   

   Creating annotated heatmaps   

   Image antialiasing   

   Clipping images with patches   

   Image Demo   

   Image Masked   

   Image Nonuniform   

   Blend transparency with color in 2D images   

   Modifying the coordinate formatter   

   Interpolations for imshow   

   Contour plot of irregularly spaced data   

   Multi Image   

   Pcolor Demo   

   pcolormesh grids and shading   

   pcolormesh   

   QuadMesh Demo   

   Advanced quiver and quiverkey functions   

   Quiver Simple Demo   

   Shading example   

   Spectrogram Demo   

   Spy Demos   

   Tricontour Demo   

   Tricontour Smooth Delaunay   

   Tricontour Smooth User   

   Trigradient Demo   

   Triinterp Demo   

   Tripcolor Demo   

   Triplot Demo   

   Watermark image   

   Axes box aspect   

   Axes Demo   

   Controlling view limits using margins and sticky_edges   

   Axes Props   

   axhspan Demo   

   Equal axis aspect ratio   

   Axis Label Position   

   Broken Axis   

   Placing Colorbars   

   Resizing axes with constrained layout   

   Resizing axes with tight layout   

   Different scales on the same axes   

   Figure size in different units   

   Figure labels: suptitle, supxlabel, supylabel   

   Creating adjacent subplots   

   Combining two subplots using subplots and GridSpec   

   Invert Axes   

   Secondary Axis   

   Figure subfigures   

   Multiple subplots   

   Creating multiple subplots using plt.subplots   

   Plots with different scales   

   Zoom region inset axes   

   Percentiles as horizontal bar chart   

   Artist customization in box plots   

   Box plots with custom fill colors   

   Boxplots   

   Box plot vs. violin plot comparison   

   Boxplot drawer function   

   Plot a confidence ellipse of a two-dimensional dataset   

   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   

   Hexagonal binned plot   

   Histograms   

   Using histograms to plot a cumulative distribution   

   Some features of the histogram (hist) function   

   Demo of the histogram function's different histtype settings   

   The histogram (hist) function with multiple data sets   

   Producing multiple histograms side by side   

   Time Series Histogram   

   Violin plot basics   

   Basic pie chart   

   Pie Demo2   

   Bar of pie   

   Nested pie charts   

   Labeling a pie and a donut   

   Polar plot   

   Using accented text in matplotlib   

   Scale invariant angle label   

   Annotating Plots   

   Composing Custom Legends   

   Date tick labels   

   Custom tick formatter for time series   

   AnnotationBbox demo   

   Using a text as a Path   

   Labeling ticks using engineering notation   

   Figure legend demo   

   Configuring the font family   

   Using a ttf font file in Matplotlib   

   Font table   

   Legend using pre-defined labels   

   Legend Demo   

   Artist within an artist   

   Mathtext   

   Math fontfamily   

   Multiline   

   Placing text boxes   

   Rendering math equations using TeX   

   Precise text layout   

   Default text rotation demonstration   

   Text Rotation Relative To Line   

   Title positioning   

   Text watermark   

   Align y-labels   

   Annotate Transform   

   Annotating a plot   

   Programmatically controlling subplot adjustment   

   Boxplot Demo   

   Dollar Ticks   

   Color Demo   

   Color by y-value   

   Colors in the default property cycle   

   Colorbar   

   Colormap reference   

   Creating a colormap from a list of colors   

   List of named colors   

   Arrow guide   

   Reference for Matplotlib artists   

   Line, Poly and RegularPoly Collection with autoscaling   

   Compound path   

   Dolphins   

   Mmh Donuts!!!   

   Ellipse Collection   

   Ellipse Demo   

   Drawing fancy boxes   

   Hatch style reference   

   Line Collection   

   Circles, Wedges and Polygons   

   PathPatch object   

   Bezier Curve   

   Bayesian Methods for Hackers style sheet   

   Dark background style sheet   

   FiveThirtyEight style sheet   

   ggplot style sheet   

   Grayscale style sheet   

   Style sheets reference   

   Anchored Direction Arrow   

   HBoxDivider demo   

   Showing RGB channels using RGBAxes   

   Adding a colorbar to inset axes   

   Colorbar with AxesDivider   

   Controlling the position and size of colorbars with Inset Axes   

   Inset Locator Demo   

   Inset Locator Demo2   

   Scatter Histogram (Locatable Axes)   

   Simple Anchored Artists   

   Bachelor's degrees by gender   

   Integral as the area under a curve   

   Decay   

   Animated histogram   

   pyplot animation   

   The Bayes update   

   Animated image using a precomputed list of images   

   Pausing and Resuming an Animation   

   Animated line plot   

   Oscilloscope   

   Mouse move and click events   

   Data Browser   

   Figure/Axes enter and leave events   

   Image Slices Viewer   

   Keypress event   

   Legend Picking   

   Looking Glass   

   Path Editor   

   Pick Event Demo   

   Pick Event Demo2   

   Poly Editor   

   Pong   

   Resampling Data   

   Timers   

   Trifinder Event Demo   

   Viewlims   

   Zoom Window   

   Frontpage 3D example   

   Frontpage contour example   

   Frontpage histogram example   

   Frontpage plot example   

   Anchored Artists   

   Changing colors of lines intersecting a box   

   Manual Contour   

   Coords Report   

   Cross hair cursor   

   Custom projection   

   AGG filter   

   Ribbon Box   

   Findobj Demo   

   Building histograms using Rectangles and PolyCollections   

   Plotting with keywords   

   Multiprocess   

   Packed-bubble chart   

   Patheffect Demo   

   Pythonic Matplotlib   

   Rasterization for vector graphics   

   TickedStroke patheffect   

   Zorder Demo   

   Custom hillshading in a 3D surface plot   

   3D stem   

   3D surface (colormap)   

   3D wireframe plots in one direction   

   Loglog Aspect   

   Log Bar   

   Log Demo   

   Log Axis   

   Logit Demo   

   Exploring normalizations   

   Scales   

   Symlog Demo   

   Hillshading   

   Anscombe's quartet   

   Left ventricle bullseye   

   MRI   

   Radar chart (aka spider or star chart)   

   Topographic hillshading   

   Centered spines with arrows   

   Multiple Yaxis With Spines   

   Spines   

   Custom spine bounds   

   Dropped spines   

   Automatically setting tick positions   

   Centering labels between ticks   

   Colorbar Tick Labelling   

   Custom Ticker1   

   Formatting date ticks using ConciseDateFormatter   

   Date Demo Convert   

   Placing date ticks using recurrence rules   

   Date Index Formatter   

   Date Precision and Epochs   

   Major and minor ticks   

   The default tick formatter   

   Tick formatters   

   Tick locators   

   Set default y-axis tick labels on the right   

   Setting tick labels from a list of values   

   Set default x-axis tick labels on the top   

   Annotation with units   

   Artist tests   

   Bar demo with units   

   Group barchart with units   

   Evans test   

   Radian ticks   

   Inches and Centimeters   

   Unit handling   

   pyplot with GTK3   

   pyplot with GTK4   

   SVG Tooltip   

   Anchored Box04   

   Annotate Explain   

   Annotate Simple01   

   Annotate Simple02   

   Annotate Simple03   

   Annotate Simple04   

   Annotate Simple Coord01   

   Annotate Simple Coord02   

   Annotate Simple Coord03   

   Annotate Text Arrow   

   Interactive Adjustment of Colormap Range   

   Colormap Normalizations   

   Colormap Normalizations Symlognorm   

   Connect Simple01   

   Connection styles for annotations   

   Custom box styles   

   Pgf Fonts   

   Pgf Preamble   

   Pgf Texsystem   

   Simple Annotate01   

   Simple Legend02   

   Annotated Cursor   

   Buttons   

   Check Buttons   

   Cursor   

   Lasso Selector   

   Mouse Cursor   

   Multicursor   

   Polygon Selector   

   Radio Buttons   

   Thresholding an Image with RangeSlider   

   Slider   

   Snapping Sliders to Discrete Values   

   Span Selector   

   Textbox   

   Basic Usage   

   The Lifecycle of a Plot   

   Artist tutorial   

   Legend guide   

   Styling with cycler   

   Constrained Layout Guide   

   Tight Layout guide   

   Arranging multiple Axes in a Figure   

   Autoscaling   

   Faster rendering by using blitting   

   Path Tutorial   

   Transformations Tutorial   

   Specifying Colors   

   Customized Colorbars Tutorial   

   Creating Colormaps in Matplotlib   

   Colormap Normalization   

   Choosing Colormaps in Matplotlib   

   Text in Matplotlib Plots   

   Annotations   

   plot(x, y)   

   scatter(x, y)   

   bar(x, height) / barh(y, width)   

   stem(x, y)   

   step(x, y)   

   fill_between(x, y1, y2)   

   imshow(Z)   

   pcolormesh(X, Y, Z)   

   contour(X, Y, Z)   

   contourf(X, Y, Z)   

   barbs(X, Y, U, V)   

   quiver(X, Y, U, V)   

   streamplot(X, Y, U, V)   

   hist(x)   

   boxplot(X)   

   errorbar(x, y, yerr, xerr)   

   violinplot(D)   

   eventplot(D)   

   hist2d(x, y)   

   hexbin(x, y, C)   

   pie(x)   

   tricontour(x, y, z)   

   tricontourf(x, y, z)   

   tripcolor(x, y, z)   

   triplot(x, y)