Matplotlib subplots() Function

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 2×1 vertical2×1 horizontal or a 2×2 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, ncolsThe 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, shareyTo control the sharing of properties among x (sharex) or among y (sharey) axis these parameters are used.
  • squeezeThis optional parameter usually contains boolean values with the default is True.
  • subplot_kwThis 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_kwThis 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:

  • fig: This method is used to return the figure layout.
  • ax: This method is mainly used to return the axes. It can be an Axes object or an array of Axes objects.

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

The output for the above code is as follows:

Matplotlib subplots function example

Let us cover a live example to understand this function in more detail.


Let us understand the code of the live example which is given below in which we have plotted two sub plots.

Follow Us On