
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Create Multiple Plots Iteratively in Python using Matplotlib
Matplotlib is a popular Python package that is used for data visualization. Visualizing data is a key step since it helps understand what is going on in the data without actually looking at the numbers and performing complicated computations. It helps in communicating the quantitative insights to the audience effectively.
Matplotlib is used to create 2 dimensional plots with the data. It comes with an object oriented API that helps in embedding the plots in Python applications. Matplotlib can be used with IPython shells, Jupyter notebook, Spyder IDE and so on.
It is written in Python. It is created using Numpy, which is the Numerical Python package in Python.
Python can be installed on Windows using the below command −
pip install matplotlib
The dependencies of Matplotlib are −
Python ( greater than or equal to version 3.4) NumPy Setuptools Pyparsing Libpng Pytz Free type Six Cycler Dateutil
Let us understand how Matplotlib can be used to multiple plots in the same plot iteratively −
Example
import numpy as np import matplotlib.pyplot as plt fig = plt.figure() fig.subplots_adjust(top=0.8) ax1 = fig.add_subplot(211) ax1.set_ylabel('Y−axis') ax1.set_title('A simple plot') t = np.arange(0.0, 1.0, 0.01) s = np.sin(2*np.pi*t) line, = ax1.plot(t, s, color='blue', lw=2) np.random.seed(4567232) ax2 = fig.add_axes([0.15, 0.1, 0.8, 0.3]) n, bins, patches = ax2.hist(np.random.randn(1000), 50, facecolor='yellow', edgecolor='green') ax2.set_xlabel('x−label') plt.show()
Output
Explanation
The required packages are imported and its alias is defined for ease of use.
An empty figure is created using the ‘figure’ function.
The ‘subplot’ function is used to create an area to plot the graph.
The data values are created using the NumPy library.
The ‘random’ library’s ‘seed’ function is used to create data points.
The ‘add_subplot’ is used to create another new subplot to the newly created plot.
The data is plotted using the ‘plot’ function.
The set_xlabel, set_ylabel and set_title functions are used to provide labels for ‘X’ axis, ‘Y’ axis and title.
It is shown on the console using the ‘show’ function.