In this tutorial, you’ll learn about matplotlib, the plotting library of Python. You’ll also get to learn how do we use it for plotting different types of graphs in Python.
What is Matplotlib?
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays. You can make a bar graph, line graph, scatter graph, mathematical graphs along with various 3D graphs.
Plotting a Line Graph
First of all, open your Python IDE. Click here to download one. You need to import matplotlib.pyplot for all these tasks, which is a collection of command style functions. Here are the code and output.
import matplotlib.pyplot as plt #using the matplotlib.pyplot
x=[1,2,3]
y=[4,5,1]
plt.plot(x,y) #plots the graph
plt.show() #this is responsible for 'printing' the graph
Adding the labels to the graph
Since the graph has been successfully made but it lacks the basic information like the labels, heading etc. So let’s add that now.
import matplotlib.pyplot as plt
x=[1,2,3]
y=[4,6,5]
plt.plot(x,y)
plt.title('info') #.title() for the heading of the graph
plt.xlabel('x-axis') #.xlabel() for the x-coordinate
plt.ylabel('y-axis') #.ylabel() for the y-coordinate
plt.show()
Adding styles to your graph
Till now, you would have successfully made the graph but it is very basic. To add various styles like the line width, gridlines, legends, etc. Let’s see how it is done!
import matplotlib.pyplot as plt
x=[5,8,10]
y=[4,12,8]
x2=[4,8,9]
y2=[5,7,11]
plt.plot(x,y,label='line 1',linewidth=5) #adding more attributes of .plot()
plt.plot(x2,y2,label='line 2',linewidth=5)
plt.title('Info')
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.legend() # to add the legends we use .legend()
plt.grid(True,color='k')
# .grid() is used to draw the lines, here k denotes black color of the grid lines
plt.show()
Plotting the Bar graph
To plot a bar graph, you need to use .bar() method of pyplot. Here is the code and the output.
import matplotlib.pyplot as plt
x=[5,7,9]
y=[4,12,8]
x2=[4,6,8]
y2=[5,7,11]
plt.bar(x,y,label="example 1")
plt.bar(x2,y2,label="example 2")
plt.legend()
plt.title('Epic Info')
plt.xlabel('number')
plt.ylabel('height')
plt.show()
Using the Scatter Plot
You can easily draw a scatter plot too by doing some small changes. Refer this code for it.
import matplotlib.pyplot as plt
x=[1,2,3,4,5,6,7,8]
y=[5,2,4,2,1,4,5,2]
plt.scatter(x,y,label="trend 1",marker='o',color='g') #marker is the symbol of the plot
plt.legend()
plt.title('Scatter plot')
plt.xlabel('x')
plt.ylabel('y')
plt.show()
Using Numpy with Matplotlib
I hope you were able to understand about Matplotlib. Apart from this, we can also use it to draw mathematical functions using Numpy, another potential library in Python.
import matplotlib.pyplot as plt
import numpy as np
x=np.arange(0,6.5,0.1) #.arange([start],[stop],[counter])
y=np.sin(x)
plt.plot(x,y)
plt.show()
So far, you have seen the default Matplotlib GUI. Now, we will create some Tkinter GUIs using Matplotlib.
This will require a few more lines of Python code and importing some more libraries, and it is well worth the effort, because we are gaining control of our paintings using canvases.
Using Tkinter with Matplotlib
We will be using Figure in combination with Canvas. It creates a more custom-made graph, which looks much better and also enables us to add buttons and other widgets to it.
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import tkinter as tk
fig = Figure(figsize=(12, 8), facecolor='white')
# axis = fig.add_subplot(111) # 1 row, 1 column, only graph
axis = fig.add_subplot(211) # 2 rows, 1 column, Top graph
xValues = [1,2,3,4]
yValues = [6,8,12,10]
axis.plot(xValues, yValues)
axis.set_xlabel('Horizontal Label')
axis.set_ylabel('Vertical Label')
# axis.grid() # default line style
axis.grid(linestyle='-') # solid grid lines
def _destroyWindow():
root.quit()
root.destroy()
root = tk.Tk()
root.withdraw()
root.protocol('WM_DELETE_WINDOW', _destroyWindow)
canvas = FigureCanvasTkAgg(fig, master=root)
canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1)
root.update()
root.deiconify()
root.mainloop()
You need to remember that the matplotlib is being used along with Tkinter. So all the tasks which we saw in this blog above, can be incorporated by using the GUI of the Tkinter. Now, you can also place labels in this window. Let’s see how it’s done!
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import tkinter as tk
fig = Figure(figsize=(12, 5), facecolor='white')
axis = fig.add_subplot(111) # 1 row, 1 column
xValues = [1,2,3,4]
yValues0 = [6,7.5,8.5,7.5]
yValues1 = [5.5,6.5,8.5,6]
t0, = axis.plot(xValues, yValues0)
t1, = axis.plot(xValues, yValues1)
axis.set_ylabel('Vertical Label')
axis.set_xlabel('Horizontal Label')
axis.grid()
fig.legend((t0, t1), ('First line', 'Second line'), 'upper right')
def _destroyWindow():
root.quit()
root.destroy()
root = tk.Tk()
root.withdraw()
root.protocol('WM_DELETE_WINDOW', _destroyWindow)
canvas = FigureCanvasTkAgg(fig, master=root)
canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1)
root.update()
root.deiconify()
root.mainloop()
There are many other commands and methods under Matplotlib, Numpy and Tkinter which are a very great tool in today’s era. Let me know in the comment section. Happy learning!