# How to use add_subplot() in matplotlib

In this post, we will discuss one of the most used functions in matplotlib. At the end of this article, you will know how to use add_subplot() in matplotlib. If there is a need for you to be here, it is good to assume that you have already installed matplotlib on your machine.

However, a short description of the installation is provided. Feel free to skip it if you have already installed matplotlib.

## Installation of matplotlib

It is often a good idea to use the Python package manager pip for installing packages so you don’t have version conflicts. To install matplotlib, run the following command on your command prompt.

pip install matplotlib

This should install everything that’s necessary. Import the package on your Python shell to check if it was installed correctly.

## The use of matplotlib add_subplot()

First, let’s see what a subplot actually means. A subplot is a way to split the available region into a grid of plots so that we will be able to plot multiple graphs in a single window. You might need to use this when there’s is a need for you to show multiple plots at the same time.

The add_subplot() has 3 arguments. The first one being the number of rows in the grid, the second one being the number of columns in the grid and the third one being the position at which the new subplot must be placed.

Example usage for the above is:

from matplotlib import pyplot as plt fig = plt.figure() # Adds a subplot at the 1st position fig.add_subplot(2, 2, 1) plt.plot([1, 2, 3], [1, 2, 3]) # Adds a subplot at the 4th position fig.add_subplot(2, 2, 4) plt.plot([3, 2, 1], [1, 2, 3]) fig.show()

The output for the above code is:

It is to be noted that fig.add_subplot(2, 2, 1) is equivalent to fig.add_subplot(221). The arguments can be specified as a sequence without separating them by commas. You can plot the subplots by using the plot function of pyplot. The subplots will be filled in the order of plotting.

I hope you found this article helpful for understanding add_subplot() in matplotlib.

See also:

## Leave a Reply

You must be logged in to post a comment.