How to plot many subplots in Matplotlib?

To create multiple plots use matplotlib.pyplot.suplots method which returns the figure along with Axes object or array of Axes object. nrows, ncols attributes of subplots() method determine the number of rows and columns of the subplot grid.

By default, it returns a figure with a single plot. For each axes object i.e plot we can set title (set via set_title()), an x-label (set via set_xlabel()), and a y-label set via set_ylabel()).

  1. When we call the subplots() method by stacking only in one direction it returns a 1D array of axes object i.e subplots.
  2. We can access these axes objects using indices just like we access elements of the array. To create specific subplots, call matplotlib.pyplot.plot() on the corresponding index of the axes. Refer to the following figure for a better understanding

Example:

# importing library 
import matplotlib.pyplot as plt 
# Some data to display 
x = [1, 2, 3] 
y = [0, 1, 0] 
z = [1, 0, 1] 

# Creating 2 subplots 
fig, ax = plt.subplots(2) 

# Accessing each axes object to plot the data through returned array 
ax[0].plot(x, y) 
ax[1].plot(x, z)