Matplotlib subplots() Function
In this tutorial, we will cover the subplots()
function in the state-based interface Pyplot in the Matplotlib Library.
The subplots()
function in the Matplotlib acts as a utility wrapper. This function helps in creating common layouts of subplots and it also includes the enclosing figure object, in a single call.
-
The main objective of this function is to create a figure with a set of subplots.
-
Various kind of subplots supported by matplotlib is 2x1 vertical, 2x1 horizontal or a 2x2 grid.
Matplotlib subplots()
Function
The basic syntax to use this function is as follows:
matplotlib.pyplot.subplots(nrows, ncols, sharex, sharey, squeeze, subplot_kw, gridspec_kw, **fig_kw)
Matplotlib subplots()
Function Parameters
Let us discuss the parameters used by this function:
-
nrows, ncols
The parameter nrows is used to indicate the number of rows and the parameter ncols is used to indicate the number of columns of the subplot grid.
-
sharex, sharey
To control the sharing of properties among x (sharex) or among y (sharey) axis these parameters are used.
-
squeeze
This optional parameter usually contains boolean values with the default is True.
-
subplot_kw
This parameter is used to indicate the dict with keywords that are passed to the add_subplot call which is used to create each subplot.
-
gridspec_kw
This parameter is used to indicate the dict with keywords passed to the GridSpec constructor that is used to create the grid on which the subplots are placed on.
Matplotlib subplots()
Function Returned Values
The values returned by these function are as follows:
Let us understand this method with the help of a few examples:
Example 1:
With the given below code snippet, we will create a figure having 2 rows and 2 columns of subplots.
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(2, 2)
x = np.linspace(0, 8, 1000)
ax[0, 0].plot(x, np.sin(x), 'c') #row=0, col=0
ax[1, 0].plot(x, np.tan(x), 'r') #row=1, col=0
ax[0, 1].plot(range(50), 'y') #row=0, col=1
ax[1, 1].plot(x, np.cos(x), 'k') #row=1, col=1
fig.show()
The output for the above code is as follows:
Let us cover a live example to understand this function in more detail.
Example2
Let us understand the code of the live example which is given below in which we have plotted two sub plots.
Summary:
If you want to create multiple sub plots in a single figure to show different aspects of a data, then the subplots()
function should be used.