
- Matplotlib - Home
- Matplotlib - Introduction
- Matplotlib - Vs Seaborn
- Matplotlib - Environment Setup
- Matplotlib - Anaconda distribution
- Matplotlib - Jupyter Notebook
- Matplotlib - Pyplot API
- Matplotlib - Simple Plot
- Matplotlib - Saving Figures
- Matplotlib - Markers
- Matplotlib - Figures
- Matplotlib - Styles
- Matplotlib - Legends
- Matplotlib - Colors
- Matplotlib - Colormaps
- Matplotlib - Colormap Normalization
- Matplotlib - Choosing Colormaps
- Matplotlib - Colorbars
- Matplotlib - Working With Text
- Matplotlib - Text properties
- Matplotlib - Subplot Titles
- Matplotlib - Images
- Matplotlib - Image Masking
- Matplotlib - Annotations
- Matplotlib - Arrows
- Matplotlib - Fonts
- Matplotlib - Font Indexing
- Matplotlib - Font Properties
- Matplotlib - Scales
- Matplotlib - LaTeX
- Matplotlib - LaTeX Text Formatting in Annotations
- Matplotlib - PostScript
- Matplotlib - Mathematical Expressions
- Matplotlib - Animations
- Matplotlib - Celluloid Library
- Matplotlib - Blitting
- Matplotlib - Toolkits
- Matplotlib - Artists
- Matplotlib - Styling with Cycler
- Matplotlib - Paths
- Matplotlib - Path Effects
- Matplotlib - Transforms
- Matplotlib - Ticks and Tick Labels
- Matplotlib - Radian Ticks
- Matplotlib - Dateticks
- Matplotlib - Tick Formatters
- Matplotlib - Tick Locators
- Matplotlib - Basic Units
- Matplotlib - Autoscaling
- Matplotlib - Reverse Axes
- Matplotlib - Logarithmic Axes
- Matplotlib - Symlog
- Matplotlib - Unit Handling
- Matplotlib - Ellipse with Units
- Matplotlib - Spines
- Matplotlib - Axis Ranges
- Matplotlib - Axis Scales
- Matplotlib - Axis Ticks
- Matplotlib - Formatting Axes
- Matplotlib - Axes Class
- Matplotlib - Twin Axes
- Matplotlib - Figure Class
- Matplotlib - Multiplots
- Matplotlib - Grids
- Matplotlib - Object-oriented Interface
- Matplotlib - PyLab module
- Matplotlib - Subplots() Function
- Matplotlib - Subplot2grid() Function
- Matplotlib - Anchored Artists
- Matplotlib - Manual Contour
- Matplotlib - Coords Report
- Matplotlib - AGG filter
- Matplotlib - Ribbon Box
- Matplotlib - Fill Spiral
- Matplotlib - Findobj Demo
- Matplotlib - Hyperlinks
- Matplotlib - Image Thumbnail
- Matplotlib - Plotting with Keywords
- Matplotlib - Create Logo
- Matplotlib - Multipage PDF
- Matplotlib - Multiprocessing
- Matplotlib - Print Stdout
- Matplotlib - Compound Path
- Matplotlib - Sankey Class
- Matplotlib - MRI with EEG
- Matplotlib - Stylesheets
- Matplotlib - Background Colors
- Matplotlib - Basemap
- Matplotlib - Event Handling
- Matplotlib - Close Event
- Matplotlib - Mouse Move
- Matplotlib - Click Events
- Matplotlib - Scroll Event
- Matplotlib - Keypress Event
- Matplotlib - Pick Event
- Matplotlib - Looking Glass
- Matplotlib - Path Editor
- Matplotlib - Poly Editor
- Matplotlib - Timers
- Matplotlib - Viewlims
- Matplotlib - Zoom Window
- Matplotlib Widgets
- Matplotlib - Cursor Widget
- Matplotlib - Annotated Cursor
- Matplotlib - Buttons Widget
- Matplotlib - Check Buttons
- Matplotlib - Lasso Selector
- Matplotlib - Menu Widget
- Matplotlib - Mouse Cursor
- Matplotlib - Multicursor
- Matplotlib - Polygon Selector
- Matplotlib - Radio Buttons
- Matplotlib - RangeSlider
- Matplotlib - Rectangle Selector
- Matplotlib - Ellipse Selector
- Matplotlib - Slider Widget
- Matplotlib - Span Selector
- Matplotlib - Textbox
- Matplotlib Plotting
- Matplotlib - Line Plots
- Matplotlib - Area Plots
- Matplotlib - Bar Graphs
- Matplotlib - Histogram
- Matplotlib - Pie Chart
- Matplotlib - Scatter Plot
- Matplotlib - Box Plot
- Matplotlib - Arrow Demo
- Matplotlib - Fancy Boxes
- Matplotlib - Zorder Demo
- Matplotlib - Hatch Demo
- Matplotlib - Mmh Donuts
- Matplotlib - Ellipse Demo
- Matplotlib - Bezier Curve
- Matplotlib - Bubble Plots
- Matplotlib - Stacked Plots
- Matplotlib - Table Charts
- Matplotlib - Polar Charts
- Matplotlib - Hexagonal bin Plots
- Matplotlib - Violin Plot
- Matplotlib - Event Plot
- Matplotlib - Heatmap
- Matplotlib - Stairs Plots
- Matplotlib - Errorbar
- Matplotlib - Hinton Diagram
- Matplotlib - Contour Plot
- Matplotlib - Wireframe Plots
- Matplotlib - Surface Plots
- Matplotlib - Triangulations
- Matplotlib - Stream plot
- Matplotlib - Ishikawa Diagram
- Matplotlib - 3D Plotting
- Matplotlib - 3D Lines
- Matplotlib - 3D Scatter Plots
- Matplotlib - 3D Contour Plot
- Matplotlib - 3D Bar Plots
- Matplotlib - 3D Wireframe Plot
- Matplotlib - 3D Surface Plot
- Matplotlib - 3D Vignettes
- Matplotlib - 3D Volumes
- Matplotlib - 3D Voxels
- Matplotlib - Time Plots and Signals
- Matplotlib - Filled Plots
- Matplotlib - Step Plots
- Matplotlib - XKCD Style
- Matplotlib - Quiver Plot
- Matplotlib - Stem Plots
- Matplotlib - Visualizing Vectors
- Matplotlib - Audio Visualization
- Matplotlib - Audio Processing
- Matplotlib Useful Resources
- Matplotlib - Quick Guide
- Matplotlib - Cheatsheet
- Matplotlib - Useful Resources
- Matplotlib - Discussion
Matplotlib - Subplots() Function
In the context of data visualization, subplots refer to a layout within a single figure where multiple plots (or axes) are arranged in rows and columns. It is a common and useful task, especially when you want to display multiple plots within the same figure for analysing different aspects of data.
In Matplotlib, the subplots() function is a powerful tool for creating subplot layouts (means groups of axes) within a single figure.
Understanding subplots() Function
The subplots() function is a part of the Matplotlib library and is available in both matplotlib interfaces, the object-oriented approach (matplotlib.figure.Figure.subplots()) and the functional interface (matplotlib.pyplot.subplots()).
The matplotlib.figure.Figure.subplots() method is called on a Figure object and returns an Axes or array of Axes.
The matplotlib.pyplot.subplots() function is a wrapper for matplotlib.figure.Figure.subplots() and directly creates a figure object along with an axes or array of axes object.
Following is the syntax of the function −
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)
Here are the details of its parameters −
Both matplotlib.figure.Figure.subplots() and matplotlib.pyplot.subplots() accept several parameters to customize the subplot layout.
- nrows, ncols: Number of rows and columns of the subplot grid.
- sharex, sharey: Controls sharing of properties among x or y axes.
- squeeze: Controls the squeezing of extra dimensions from the returned array of axes.
- subplot_kw: Dictionary with keywords passed to the add_subplot call used to create each subplot.
- gridspec_kw: Dictionary with keywords passed to the GridSpec constructor used to create the grid the subplots are placed on.
- Additional keyword arguments are passed to the pyplot.figure() call.
Creating Subplots
Creating subplots is straightforward and can be achieved by simply calling the subplot() function. This will allows you to create a simple figure with only one subplot or to define a grid layout for multiple subplots within the same figure.
By specifying the number of rows and columns in the subplot grid, you can control the layout of the subplots.
Example
Here is an example that uses the matplotlib.pyplot.subplots() method to create a simple figure with only one subplot.
import matplotlib.pyplot as plt import numpy as np # First create sample 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') plt.show()
Output
On executing the above code we will get the following output −

Example
Here is the object-oriented approach to create a simple figure with only one subplot.
import matplotlib.pyplot as plt import numpy as np # First create sample data x = np.linspace(0, 2*np.pi, 400) y = np.cos(x**2) # Create a figure fig = plt.figure() # Create a subplot ax = fig.subplots() ax.plot(x, y) ax.set_title('Simple plot') plt.show()
Output
On executing the above code we will get the following output −

Accessing Subplots
Subplots can be accessed by unpacking the output array immediately after creation or can be accessed by using indexing on the axes array.
Example
In this example, subplots are accessed through unpacking the output array immediately after creation.
import matplotlib.pyplot as plt import numpy as np # First create sample data x = np.linspace(0, 2*np.pi, 400) y = np.sin(x**2) # Create two subplots and unpack the output array immediately fig, (ax1, ax2) = plt.subplots(1, 2) ax1.plot(x, y) ax2.scatter(x, y) plt.suptitle('Two Subplots') plt.show()
Output
On executing the above code we will get the following output −

Example
In this example subplots are access through index of the axes array. And legend is add to the each subplot.
import matplotlib.pyplot as plt import numpy as np # First create sample data x = np.linspace(0, 2*np.pi, 400) y = np.cos(x**2) # Create a figure fig = plt.figure() # Create a subplot axes = fig.subplots(2, 2) axes[0, 0].plot(x, y, label='cos') axes[0, 0].legend() axes[0, 1].plot(np.exp(x), label='Exponential') axes[0, 1].legend() axes[1, 0].plot(np.log10(x), label='Log') axes[1, 0].legend() axes[1, 1].scatter(x, y, label='Scatter') axes[1, 1].legend() plt.show()
Output
On executing the above code we will get the following output −

Sharing Axes
The subplots() function also allows you to control the sharing of properties among x or y axes using the sharex and sharey parameters. This can be useful for ensuring consistency in axis scaling and tick labeling across subplots.
Example
This example demonstrates how to create a grid of subplots that share the same y-axis.
import matplotlib.pyplot as plt import numpy as np # First create sample data x = np.arange(1, 5) # Create a figure fig = plt.figure() plt.title('Sharing Axes') # Create a subplot axes = fig.subplots(2, 2, sharey=True) axes[0, 0].plot(x,x*x) axes[0, 1].plot(x,np.sqrt(x)) axes[1, 0].plot(x,np.exp(x)) axes[1, 1].plot(x,np.log10(x)) plt.show()
Output
On executing the above code we will get the following output −
