Plotting graphs with Matplotlib (Python)

by Apr 6, 2020Python Tkinter

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
Output: Line 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 heading and the labels

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()

Output graph

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()
Output Bar graph

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()
Output Scatter Plot

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()
Sin(x) graph using Numpy

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()

Output: Tkinter GUI

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()
Output

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!

Creating a multiplication Skill in Alexa using python

Written By Anmol Punetha

Hey, I am Anmol. I am a tech blogger and an electronics engineering student at the same time. As you're reading my blog, you are getting a generous amount of information in simpler words. Hope it's of use. Thank you for visiting. Keep reading!

RELATED POSTS

Data And Classes in Python Tkinter

Data And Classes in Python Tkinter

In this article, we are going to learn about data and classes in python Tkinter. We will save our GUIdata into Tkinter variables after that we will also start using OOP to extend the existing Tkinter classes to extend the built-in functionality of Tkinter....

Python Tkinter MessageBox-Example

Python Tkinter MessageBox-Example

INTRODUCTION In this article, we will learn “How to interface the radio button and messages with Tkinter”. I recommend you to go through this first similarly if you are new to Tkinter go through this. Here we will design a GUI with a 4 radio button and...

asksaveasfile() function in Python-Tkinter

asksaveasfile() function in Python-Tkinter

In this tutorial, we will be learning how to use the asksaveasfile() in Tkinter and save the file in the system. The asksaveasfile() function comes under the class filedialog. The file dialog module provides functions for creating file/directory selection...

Graphical User Interface with tkinter python

Graphical User Interface with tkinter python

In this article, we will tell about the GUI(graphical user interface) in python using. We should also know about how to import the library and using some widgets in it. Let’s have a quick look at the below contents. Contents IntroductionWhat is Tkinter?Packaging...

VIDEOS – FOLLOW US ON YOUTUBE

EXPLORE OUR IOT PROJECTS

IoT Smart Gardening System – ESP8266, MQTT, Adafruit IO

Gardening is always a very calming pastime. However, our gardens' plants may not always receive the care they require due to our active lifestyles. What if we could remotely keep an eye on their health and provide them with the attention they require? In this article,...

How to Simulate IoT projects using Cisco Packet Tracer

In this tutorial, let's learn how to simulate the IoT project using the Cisco packet tracer. As an example, we shall build a simple Home Automation project to control and monitor devices. Introduction Firstly, let's quickly look at the overview of the software. Packet...

All you need to know about integrating NodeMCU with Ubidots over MQTT

In this tutorial, let's discuss Integrating NodeMCU and Ubidots IoT platform. As an illustration, we shall interface the DHT11 sensor to monitor temperature and Humidity. Additionally, an led bulb is controlled using the dashboard. Besides, the implementation will be...

All you need to know about integrating NodeMCU with Ubidots over Https

In this tutorial, let's discuss Integrating NodeMCU and Ubidots IoT platform. As an illustration, we shall interface the DHT11 sensor to monitor temperature and Humidity. Additionally, an led bulb is controlled using the dashboard. Besides, the implementation will be...

How to design a Wireless Blind Stick using nRF24L01 Module?

Introduction Let's learn to design a low-cost wireless blind stick using the nRF24L01 transceiver module. So the complete project is divided into the transmitter part and receiver part. Thus, the Transmitter part consists of an Arduino Nano microcontroller, ultrasonic...

Sending Temperature data to ThingSpeak Cloud and Visualize

In this article, we are going to learn “How to send temperature data to ThingSpeak Cloud?”. We can then visualize the temperature data uploaded to ThingSpeak Cloud anywhere in the world. But "What is ThingSpeak?” ThingSpeak is an open-source IoT platform that allows...

Amaze your friend with latest tricks of Raspberry Pi and Firebase

Introduction to our Raspberry Pi and Firebase trick Let me introduce you to the latest trick of Raspberry Pi and Firebase we'll be using to fool them. It begins with a small circuit to connect a temperature sensor and an Infrared sensor with Raspberry Pi. The circuit...

How to implement Machine Learning on IoT based Data?

Introduction The industrial scope for the convergence of the Internet of Things(IoT) and Machine learning(ML) is wide and informative. IoT renders an enormous amount of data from various sensors. On the other hand, ML opens up insight hidden in the acquired data....

Smart Display Board based on IoT and Google Firebase

Introduction In this tutorial, we are going to build a Smart Display Board based on IoT and Google Firebase by using NodeMCU8266 (or you can even use NodeMCU32) and LCD. Generally, in shops, hotels, offices, railway stations, notice/ display boards are used. They are...

Smart Gardening System – GO GREEN Project

Automation of farm activities can transform agricultural domain from being manual into a dynamic field to yield higher production with less human intervention. The project Green is developed to manage farms using modern information and communication technologies....