Sunday, June 9, 2024

Importing Matplotlib and Pyplot

To import the matplotlib.pyplot library in Python you must use the import statement. The common practice is to import the matplotlib pyplot module using the plt alias for convention.
import matplotlib.pyplot as plt

Steps to import and use the matplotlib.pyplot

First you need to install the matplotlib if you have not done it so far. There are several ways how to install the matplotlib library. The first is the the most easiest using pip installer.
pip install matplotlib
If for some reason you need to upgrade the matplotlib libraray then you have to type the following.
pip install matplotlib --upgrade
In case you have to install the matplotlib using condas installer deoending on your operting system in the anaconda prompt type in one of the follwing commands.
conda install conda-forge::matplotlib
conda install conda-forge/label/broken::matplotlib
conda install conda-forge/label/broken-test::matplotlib
conda install conda-forge/label/cf201901::matplotlib
conda install conda-forge/label/cf202003::matplotlib
conda install conda-forge/label/gcc7::matplotlib
conda install conda-forge/label/matplotlib_rc::matplotlib
conda install conda-forge/label/rc::matplotlib
conda install conda-forge/label/testing::matplotlib
conda install conda-forge/label/testing/gcc7::matplotlib
When the matplotlib is successfully installed you can now import the matpltolib.pyplot library.
import matplotlib.pyplot as plt
The final step is to use the matplotlib.pyplot library is successfully installed. If that is not the case you need to install it carefuly in order to use its features. The example of simple usage is given below.
import matplotlib.pyplot as plt
x = [i for i in range(0,20,1)]
y = [i**2 for i in range(0,20,1)]
plt.plot(x,y)
plt.title("simple plot")
plt.xlabel("X-Axsis")
plt.ylabel("Y-Axis")
plt.legend(['Simple Legend'])
The explanation of the previous code is given below.
  1. Step 1 - The import matplotlib.pyplot as plt code line imports the pyplot module and gives it alias plt. Now you can sue the plt module if however, the matplotlib library is correctly installed.
  2. Step 2 - Data is prepared and in this case simple lists were used-.
  3. Step 3 - using plt.plot(x,y) the function creates a plot of y versus x variable
  4. Step 4 - The plot is customized with title, axis labels, and gird.
  5. Step 5 -

No comments:

Post a Comment