Matplotlib Multiplots with subplots() Function
In this tutorial, we will cover how to draw multiple plots in a single graph in matplotlib.
You must be thinking, why would we want to have multiple plots in a single graph. That will only lead to confusion and clutter. But if you need to either do comparison between the two curves or if you want to show some gradual changes in the plots(relative to each other), etc. in that case multiple plots are useful.
In matplotlib, we can do this using Subplots.
subplots() function is in the pyplot module of the matplotlib library and is used for creating subplots/multiplots in an effective manner.
This function will create a figure and a set of subplots. It is basically a wrapper function and which is used to create common layouts of subplots(including the enclosing figure object) in a single call.
This function mainly returns a figure and an Axes object or also an array of Axes objects.
If you use this function without any parameters then it will return a Figure object and one Axes object.
Given below is the syntax for using this function:
subplots(nrows, ncols, sharex, sharey, squeeze, subplot_kw, gridspec_kw, **fig_kw)
Let us discuss the parameters used by this function:
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. Both parameters have a default value as 1.
To control the sharing of properties among x (
sharex) or among y (
sharey) axis these parameters are used.
This optional parameter usually contains boolean values with the default is True.
This parameter is used to indicate the dict with keywords that are passed to the
add_subplotcall which is used to create each subplot.
This parameter is used to indicate the dict with keywords passed to the
GridSpecconstructor that is used to create the grid on which the subplots are placed on.
All the additional keyword arguments passed to the
.pyplot.figurecall are part of this parameter.
Now we will cover some examples so that all the concepts become clear for you.
Example1: Plot with one Figure and an Axes
The code for this example is as follows:
import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 2*np.pi, 400) y = np.sin(x**2) + np.cos(x) fig, ax = plt.subplots() ax.plot(x, y) ax.set_title('Simplest plot in the matplotlib')
Now its time to take a look the output for the code:
In this we have used the
subplots() function, but we haven't added two plots to the graph. So the
subplots() function can be normally used to create a single graph/plot as well.
Example 2: Stacked Plots
Let us cover an example for stacked plots. We will try to plot a sequence of plots (i.e 2 here) just by stacking one over the other. As there is the stacking of plots, so the number of rows (i.e
nrows) will change, which means
ncols stay the same as 1. Also, Each subplot is identified by the index parameter.
The code snippet for this is as follows:
import numpy as np import matplotlib.pyplot as plt plt.figure(figsize=(6, 4)) def f(x): return np.sin(x) - x * np.cos(x) def fp(x): """ The derivative function of f """ return x * np.sin(x) X = np.arange(-5, 5.0, 0.05) fig, ax = plt.subplots(2, sharex='col', sharey='row') ax.plot(X, f(X), 'bo', X, f(X), 'k') ax.set(title=' function f') ax.plot(X, fp(X), 'go', X, fp(X), 'k') ax.set(xlabel='X Values', ylabel='Y Values', title='Derivative Function of f') plt.show()
Here is the output of the above code:
As ou can see in the output above that two plots are stacked one on top of the other. The plot can be of some other type too. But when you want to do some comparison between plots, this is a good approach.
Example 3: Plot within another Plot
For this code example. let's take a live example.
You can use the above terminal to run the other examples too and see the output. Try making different plots too.
In this tutorial, we covered how to create multiple plots in matplotlib using the
subplots() function. We also covered different arrangements for the multiple plots in a single figure.