Plots in matplot
library (matplotlib
) are used to give a visual representation of a given data.
With the help of the pyplot
module in the matplotlib,
we could make a plot representation of given data.
A multiple plot is a situation in which there are more plots than one on the same figure. This is usually done when a programmer wants to compare or differentiate between different data values.
With the pyplot.subplot()
function in matplotlib
, we can create or draw multiple plots in one figure.
The pyplot.subplot()
function takes three parameters that help describe the layout of the figure. They include:
row
: to specify the number of plots you want on a row.column
: to specify the number of plots you want on a column.index
: to specify the index or position of the current plot (e.g., first (1
), second (2
), third (3
) etc.) in a figure.Using the parameters mentioned above, calling the subplot()
function will look like:
pyplot.subplot(2, 2, 1)
In this example, the obtained figure will contain 2 rows, 2 columns, and it is the first plot of the figure (index = 1).
pyplot.subplot(2, 3, 2)
In this example, the obtained figure will contain 2 rows, 3 columns, and it is the second plot of the figure (index = 2).
Important to note: The number of rows and columns specified must remain the same in a single code because it tells us how many rows and columns the figure contains. The index parameter will keep changing as it represents the position (1st, 2nd, 3rd, etc.) of a given plot in a figure.
Now let’s create six plots in a single figure:
import matplotlib.pyplot as pltimport numpy as npx = np.array([0, 1, 2, 3])y = np.array([3, 8, 1, 10])# the first plotplt.subplot(2, 3, 1)plt.plot(x,y)x = np.array([0, 1, 2, 3])y = np.array([10, 20, 30, 40])# the second plotplt.subplot(2, 3, 2)plt.plot(x,y)x = np.array([0, 1, 2, 3])y = np.array([3, 8, 1, 10])# the third plotplt.subplot(2, 3, 3)plt.plot(x,y)x = np.array([0, 1, 2, 3])y = np.array([10, 20, 30, 40])# the fourth plotplt.subplot(2, 3, 4)plt.plot(x,y)x = np.array([0, 1, 2, 3])y = np.array([3, 8, 1, 10])# the fifth plotplt.subplot(2, 3, 5)plt.plot(x,y)x = np.array([0, 1, 2, 3])y = np.array([10, 20, 30, 40])# the sixth plotplt.subplot(2, 3, 6)plt.plot(x,y)plt.show()
Here is a line-by-line explanation of the code above.
Lines 1-2: We import the needed modules and libraries required for the arrays and plot.
Lines 4-5: We create our data values x
and y
for the first plot.
Lines 8-9: Using the subplot()
and plot()
functions, we are able to plot y
against x
.
Lines 11-45: In these lines, we are repeating the same process for all other five plots that we did for the first plot in lines 4-5 and 8-9.
Line 47: We export all six plots to the figure using the show()
function.