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.
It is to be noted that fig.addsubplot(2, 2, 1) is equivalent to fig.addsubplot(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. Subplot(1,2,2) plot(y, x, 'g.-'); The good thing about the pylab MATLAB-style API is that it is easy to get started with if you are familiar with MATLAB, and it has a minumum of.
Since python ranges start with 0, the default x vector has the same length as y but starts with 0. Hence the x data are 0,1,2,3. Plot is a versatile command, and will take an arbitrary number of arguments. For example, to plot x versus y, you can issue the command.
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.
This should install everything that’s necessary. Import the package on your Python shell to check if it was installed correctly.
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:
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: