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 -

Basic Structure of a Pyplot Script

The basic structure of Pyplot script consist of the following components:
  1. Importing the Matplotlib library
  2. Preparing the data
  3. Creating the Plot
  4. Customizing the plot
  5. Displaying or Saving the Plot

Importing the Matplotlib library

This is basic and mandatory step. Without importing the matplotlib library there are is not showing any plots. However, the goal is to import the pyplot module from the matplotlib library.
import matplotlib.pyplot as plt

Preparing the Data

In order to plot your data you need to prepare the data. This can be done using simple Python lists, numpy arrays or pandas dataframes. As you probably know the the lists are very easy to create.
x = [i for i in range(0, 20, 1)]
y = [i**2 for i in range(0,20,1)]
The previous example is very simple. In one line we have created a list with numbers in range from 0 to 19 and store this list to variable named x. The second variable is the y variable that contains numbers from o to 19**2. Creating variables using numpy arrays is also pretty simple. All you have to do is to use np.arange function and specify range.
x = np.arange(0,20,1)
y = np.arange(0,363,19)
The definition of x is very simple i.e. use numpy function arange, define the initial value, ending value, and the step. The numpy array will contain the numbers from 0 up to 19. The initial step in y variable is from 0 up to 363 and the step is 19. The last number in the list will be 19**2 which is 361.
Regarding the pandas data frame first it is required to import the pandas library.
import pandas as pd
The pandas data frame is usually created from multiple lists or numpy array using the pd.DataFrame function.
data = pd.DataFrame([list1,list2,list3])
On the other hand the dataset used for analysis is usually stored somewhere in the .csv file. So to open it and use it simply type the pd.read_csv() function.
data=pd.read_csv("file_name.csv")

Creating the Plot

With Pyplot functions you will create the plot or graphical representation of your data.
plt.plot(x,y)

Plot Customization

Customize your plot by adding the title, x and y axis labels, plot grid, and legend.
plt.title("This is new plot")
plt.xlabel("X-Ax")
plt.ylabel("Y-Ax")
plt.grid(True)
plt.legend(["The first plot function"])

Displaying or Saving the Plot

Using the plt.show() function you can display the plot, while using the plt.savefig() you can save your figure. However, if you want to save the figure make sure that plt.show() function is commented if it is decleare before the plt.savefig function. Otherwise the plot will be blank.
plt.show() # to display the plot
plt.savefig() # To save the figure

Simple example Script

In this example we will use the previous step by step element and create a new graph. The plot will show the y versus x variable defined as lists from 0 to 19. The x variable will contain numbers from 0 to 19 including 19. While the y variable will contain numbers from 0 to 19**2.
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 result is shown in the following figure.
2024-06-10T00:48:21.468785 image/svg+xml Matplotlib v3.5.2, https://matplotlib.org/
Figure 1 - Basic plot using matplotlib.pyplot module.

What is Pyplot?

Pyplot is a Matplotlib library module that provides a MATLAB-like interface that can be used for creating and customizing plots and figures. This module offers a state-based, procedural interface for quickly and easily creating visualizations, which makes this module very useful for creating simple and quick plots. The key features of the Pyplot are a state-based interface, simple and intuitive, similar syntax like in MATLAB, comprehensive plotting capabilities, integration with numpy, customization, styling, saving, and exporting.
  • State-based interface - The pyplot module maintains a state machine which means that you can incrementally build plots. This process is similar to MATLAB. Using new/additional functions you can create and modify the current plot. The Python keeps track of the figures and axes for you.
    The state-based interface has a couple of functions that will act on a currently defined state. This differs from the object-oriented approach, where object methods are used. For example, let's say that you have the following block of code
    import matplotlib.pyplot as plt
    plt.scatter(x,y)
    The previous block of code will call the pyplot.plt module from the matplotlib library and create a scatter plot. So this code puts pyplot in a state where a current figure and current aces are defined. If the next line of code is
    plt.title("the matplotlib tutorials")
    this will create a title of the current axes that is stored in the pyplot state. The final code line will display the plot and is written as
    plt.show()
    This code will show all the figures stored in the pyplot state.
  • Simple and intuitive - The main goal when they were creating the pyplot module is that it is easy to use. Using this module the common tasks that can be achieved with a few lines of code are line plots, scatter plots, bar charts,...The simplicity of this module makes it favorable for beginners to use whi is enew in data visualization in PYthon.
The advantages of using the pyplot module are ease of use, quick prototyping, and education purposes. The state-based nature of Pyplot makes it very straightforward to create quick plots without needing to understand the underlying object-oriented structure of Matplotlib. Pyplot is excellent for prototyping and exploratory data analysis where you need to generate visualizations quickly to understand the data. The simplicity makes it an excellent tool for teaching data visualization concepts to beginners.