Matplotlib

Matplotlib is the data visualization library in Python and it allows us to generate plots, histograms, power spectra, bar charts, error charts, scatter plots, and so on, using a few lines of code. Matplotlib usually make things easier and the hardest things possible.

To use matplotlib in your Python program, first we have to install matplotlib. Run the following command in your Terminal to install matplotlib:

$ pip3 install matplotlib

Now, you have to install one more package, tkinter, for graphical representations. Install it using the following command:

$ sudo apt install python3-tk

Now that matplotlib is installed in your system, we will look at some examples. While plotting, there are two important components: figures and axes. The figure is the container that acts as the window on which everything is drawn. It can have various types of independent figures. The axis is the area where you can plot your data and any labels associated with it. Axes consist of an x axis and a y axis.

Now, we are going to look at some examples of matplotlib. Let's start with a simple example. Create a script called simple_plot.py and write the following content in it:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 5, 10)
y = x**2
plt.plot(x,y)
plt.title("sample plot")
plt.xlabel("x axis")
plt.ylabel("y axis")
plt.show()

Run the script and you will get the following output:

student@ubuntu:~/work$ python3 simple_plot.py

The output is as follows:

In the preceding example, we imported two modules, matplotlib and numpyto visualize the data as well as to create the arrays x and y, respectively. After this, we plotted two arrays as plt.plot(x,y). Then we added a title and labels to the plot using the xlabel(), ylabel()and title() functions, and to display this plotting, we used the plt.show() function. Because we are using Matplotlib within a Python script, don't forget to add plt.show() at the end line to display your plot.

Now we are going to create two arrays to display two lines of curves in the plot and we are going to apply style to both the curves. In the following example, we will use the ggplot style to plot the graph. ggplot is a system used for creating graphics declaratively, and is based on the grammar of graphics. To plot ghraph, we just provide the data and then tell ggplot how to map variables and what graphical primitives to use, and it takes care of the details. In most cases, we start with the ggplot() style.

Now, create a script called simple_plot2.py and write the following content in it:

import matplotlib.pyplot as plt
from matplotlib import style

style.use('ggplot')

x1 = [0,5,10]
y
1 = [12,16,6]
x2 = [6,9,11]
y2 = [6,16,8]

plt.subplot(2,1,1)
plt.plot(x1, y1, linewidth=3)
plt.title("sample plot")
plt.xlabel("x axis")
plt.ylabel("y axis")
plt.subplot(2,1,2)
plt.plot(x2, y2, color = 'r', linewidth=3)
plt.xlabel("x2 axis")
plt.ylabel("y2 axis")

plt.show()

Run the script and you will get the following output:

student@ubuntu:~/work$ python3 simple_plot2.py

The output is as follows:

In the preceding example, first we imported the required module, and then we used the ggplot style to plot the graph.  We created two sets of array; that is,  x1, y1 and x2, y2. Then we used the subplot function, plt.subplot(), because it allows us to plot different things within the same canvas. You can also use the plt.figure() function instead of plt.subplot(), if you want to display these two plots on a different canvas.

Now, we are going to see how to plot the arrays using the plt.figure() function and save our generated figure using Matplotlib. You can save them in different formats, such as png, jpg, pdf, and so on, by using the savefig() method. We'll save the preceding figure in a file named my_sample_plot.jpg. Now, we will look at an example. For that, create a script called simple_plot3.py and write the following content in it:

import matplotlib.pyplot as plt
from matplotlib import style

style.use('ggplot')

x1 = [0,5,10]
y1 = [12,16,6]
x2 = [6,9,11]
y2 = [6,16,8]

plt.figure(1)
plt.plot(x1, y1, color = 'g', linewidth=3)
plt.title("sample plot")
plt.xlabel("x axis")
plt.ylabel("y axis")
plt.savefig('my_sample_plot1.jpg')
plt.figure(2)

plt.plot(x2, y2, color = 'r', linewidth=3)
plt.xlabel("x2 axis")
plt.ylabel("y2 axis")
plt.savefig('my_sample_plot2.jpg')

plt.show()

Run the script and you will get the following output:

student@ubuntu:~/work$ python3 simple_plot3.py

The output is as follows:

In the preceding example, we used the plt.figure() function to plot the things on a different canvas.  After that, we used the plt.plot() function. This function has different arguments, which are useful to plot the graph. In the preceding example, we used some of arguments; that is x1, x2, y1,and y2. These are the respective axis points used to plot.

Then we  used the color argument to provide a particular color to the graph line and, in the third argument, we used linewidth, which decides the width of the graph line. After that, we also used the savefig() method to save our figure in a particular image format. You can check them in your current directory (if you did not mention the path) where you run your Python script.

You can open those images by directly accessing that directory or you can also use following method to open those generated images using matplotlib. Now, we will look at an example to open saved figures. For that, create a script called open_image.py and write the following content in it:

import matplotlib.pyplot as plt
import matplotlib.image as mpimg

plt.imshow(mpimg.imread('my_sample_plot1.jpg'))
plt.show()

Run the script and you will get the following output:

student@ubuntu:~/work$ python3 open_image.py

The output is as follows:

In the preceding example, we used the imshow() function of Matplotlib to open the saved image of the figure.

Now, we will look at different types of plots. Matplotlib allows us to create different types of plots to deal with data in arrays, such as histograms, scatter plots, bar charts, and so on. The use of different kinds of plots depends on the purpose of the data visualization. Let's look at some of these plots.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset