You are on page 1of 67

INTRODUTION TO PYTHON

WHAT IS PYTHON?
Python is a popular programming language. It was created by Guido van Rossum, and
released in 1991.
It is used for:

 web development (server-side),

 software development,

 mathematics,

 system scripting.

WHAT CAN PYTHON DO?


 Python can be used on a server to create web applications.

 Python can be used alongside software to create workflows.

 Python can connect to database systems. It can also read and modify files.

 Python can be used to handle big data and perform complex mathematics.

 Python can be used for rapid prototyping, or for production-ready software


development.

WHY PYTHON?
 Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).

 Python has a simple syntax similar to the English language.

 Python has syntax that allows developers to write programs with fewer lines than
some other programming languages.

 Python runs on an interpreter system, meaning that code can be executed as soon as
it is written. This means that prototyping can be very quick.

 Python can be treated in a procedural way, an object-oriented way or a functional


way.

GOOD TO KNOW
 The most recent major version of Python is Python 3, which we shall be using in this
tutorial. However, Python 2, although not being updated with anything other than
security updates, is still quite popular.

 In this tutorial Python will be written in a text editor. It is possible to write Python in
an Integrated Development Environment, such as Thonny, Pycharm, Netbeans or
Eclipse which are particularly useful when managing larger collections of Python
files.

PYTHON SYNTAX COMPARED TO OTHER PROGRAMMING LANGUAGES

 Python was designed for readability, and has some similarities to the English
language with influence from mathematics.

 Python uses new lines to complete a command, as opposed to other programming


languages which often use semicolons or parentheses.

 Python relies on indentation, using whitespace, to define scope; such as the scope of
loops, functions and classes. Other programming languages often use curly-brackets
for this purpose.

WHAT IS PYTHON METHOD?


You are aware of the fact that Python is an object-oriented language, right? This means that
it can deal with classes and objects to model the real world.
A Python method is a label that you can call on an object; it is a piece of code to execute on
that object.
But before we begin getting any deeper, let’s take a quick look at classes and objects.

PYTHON CLASS METHOD


A Python Class is an Abstract Data Type (ADT). Think of it like a blueprint. A rocket made
from referring to its blueprint is according to plan.
It has all the properties mentioned in the plan, and behaves accordingly. Likewise, a class is
a blueprint for an object.
To take an example, we would suggest thinking of a car. The class ‘Car’ contains properties
like brand, model, color, fuel, and so.
It also holds behavior like start(), halt(), drift(), speedup(), and turn(). An object Hyundai
Verna has the following properties then.
brand: ‘Hyundai’
model: ‘Verna’
color: ‘Black’
fuel: ‘Diesel’
Here, this is an object of the class Car, and we may choose to call it ‘car1’ or ‘blackverna’.
>>> class Car:
def __init__(self,brand,model,color,fuel):
self.brand=brand
self.model=model
self.color=color
self.fuel=fuel
def start(self):
pass
def halt(self):
pass
def drift(self):
pass
def speedup(self):
pass
def turn(self):
pass

PYTHON OBJECTS
A Python object is an instance of a class. It can have properties and behavior. We just
created the class Car.
Now, let’s create an object blackverna from this class.
Remember that you can use a class to create as many objects as you want.
>>> blackverna=Car('Hyundai','Verna','Black','Diesel')
This creates a Car object, called blackverna, with the aforementioned attributes.
We did this by calling the class like a function (the syntax).
Now, let’s access its fuel attribute. To do this, we use the dot operator in Python(.).
>>> blackverna.fuel
Output
‘Diesel’

PYTHON METHOD
A Python method is like a Python function, but it must be called on an object.
And to create it, you must put it inside a class.
Now in this Car class, we have five methods, namely, start(), halt(), drift(), speedup(), and
turn().
In this example, we put the pass statement in each of these, because we haven’t decided
what to do yet.
Let’s call the drift() Python method on blackverna.
>>> blackverna.drift()
>>>
Like a function, a method has a name, and may take parameters and have a return statement.
Let’s take an example for this.
>>> class Try:
def __init__(self):
pass
def printhello(self,name):
print(f"Hello, {name}")
return name
>>> obj=Try()
>>> obj.printhello('Ayushi')
Output
Hello, Ayushi’Ayushi’
Here, the method printhello() has a name, takes a parameter, and returns a value.
 An interesting discovery– When we first defined the class Car, we did not pass the
‘self’ parameter to the five methods of the class. This worked fine with the attributes, but
when we called the drift() method on blackverna, it gave us this error:
Output
Traceback (most recent call last):File “<pyshell#19>”, line 1, in <module>
blackverna.drift()
TypeError: drift() takes 0 positional arguments but 1 was given
From this error, we figured that we were missing the ‘self’ parameter to all those methods.
Then we added it to all of them, and called drift() on blackverna again. It still didn’t work.
Finally, we declared the blackverna object again, and then called drift() on it. This time, it
worked without an issue.
Make out of this information what you will.
__INIT__()
If you’re familiar with any other object-oriented language, you know about constructors.
In C++, a constructor is a special function, with the same name as the class, used to
initialize the class’ attributes.
Here in Python, __init__() is the method we use for this purpose.
Let’s see the __init__ part of another class.
>>> class Animal:
def __init__(self,species,gender):
self.species=species
self.gender=gender
>>> fluffy=Animal('Dog','Female')
>>> fluffy.gender
Output
‘Female’
Here, we used __init__ to initialize the attributes ‘species’ and ‘gender’.However, you don’t
need to define this function if you don’t need it in your code.
>>> class Try2:
def hello(self):
print("Hello")
>>> obj2=Try2()
>>> obj2.hello()
Init is a magic method, which is why it has double underscores before and after it.
We will learn about magic methods in a later section in this article.

PYTHON SELF PARAMETER


You would have noticed until now that we’ve been using the ‘self’ parameter with every
method, even the __init__().
This tells the interpreter to deal with the current object. It is like the ‘this’ keyword in Java.
Let’s take another code to see how this works.
>>> class Fruit:
def printstate(self,state):
print(f"The orange is {state}")
>>> orange=Fruit()
>>> orange.printstate("ripe")
Output
The orange is ripe
As you can see, the ‘self’ parameter told the method to operate on the current object, that is,
orange.
Let’s take another example.
>>> class Result:
def __init__(self,phy,chem,math):
self.phy=phy
self.chem=chem
self.math=math
def printavg(self):
print(f"Average={(self.phy+self.chem+self.math)/3}")
>>> rollone=Result(86,95,85)
>>> rollone.chem
Output
95
>>> rollone.printavg()
Output
Average=88.66666666666667
You can also assign values directly to the attributes, instead of relying on arguments.
>>> class LED:
def __init__(self):
self.lit=False
>>> obj=LED()
>>> obj.lit
Output
False
Finally, we’d like to say that ‘self’ isn’t a keyword.
You can use any name instead of it, provided that it isn’t a reserved keyword, and follows
the rules for naming an identifier.
>>> class Try3:
def __init__(thisobj,name):
thisobj.name=name
>>> obj1=Try3('Leo')
>>> obj1.name
Output
‘Leo’
This was all about the Python Self Parameter

PYTHON FUNCTIONS VS METHOD


We think we’ve learned enough about methods by now to be able to compare them to
functions.
A function differs from a method in the following ways.
1. While a method is called on an object, a function is generic.
2. Since we call a method on an object, it is associated with it. Consequently, it is able
to access and operate on the data within the class.
3. A method may alter the state of the object; a function does not, when an object is
passed as an argument to it. We have seen this in our tutorial on tuples.

PYTHON MAGIC METHODS


Another construct that Python provides us with is Python magic methods. Such a method is
identified by double underscores before and after its name.
Another name for a magic method is a dunder.
A magic method is used to implement functionality that can’t be represented as a normal
method.
__init__() isn’t the only magic method in Python; we will read more about it in a future
lesson.
But for now, we’ll just name some of the magic methods:
__add__ for +
__sub__ for –
__mul__ for *
__and__ for &
The list, however, does not end here.
This was all about the Python Method.

PYTHON ADVANTAGES
When you are learning a new language let’s say Python, you must be aware of the benefits
and drawbacks of that language.
This will help you to get a better knowledge of how you can take full advantage of the
Python programming language.
With knowing the Python advantages and disadvantages, we can build robust applications.
Let’s start with the advantages and disadvantages of Python.

ADVANTAGES OF PYTHON
1. EASY TO READ, LEARN AND WRITE
Python is a high-level programming language that has English-like syntax.
This makes it easier to read and understand the code.
Python is really easy to pick up and learn, that is why a lot of people recommend Python to
beginners.
You need less lines of code to perform the same task as compared to other major languages
like C/C++ and Java.
2. IMPROVED PRODUCTIVITY
Python is a very productive language.
Due to the simplicity of Python, developers can focus on solving the problem.
They don’t need to spend too much time in understanding the syntax or behavior of the
programming language.
You write less code and get more things done.
3. INTERPRETED LANGUAGE
Python is an interpreted language which means that Python directly executes the code line
by line.
In case of any error, it stops further execution and reports back the error which has occurred.
Python shows only one error even if the program has multiple errors.
This makes debugging easier.
4. DYNAMICALLY TYPED
Python doesn’t know the type of variable until we run the code.
It automatically assigns the data type during execution.
The programmer doesn’t need to worry about declaring variables and their data types.
5. FREE AND OPEN-SOURCE
Python comes under the OSI approved open-source license.
This makes it free to use and distribute.
You can download the source code, modify it and even distribute your version of Python.
This is useful for organizations that want to modify some specific behavior and use their
version for development.
6. VAST LIBRARIES SUPPORT
The standard library of Python is huge, you can find almost all the functions needed for your
task.
So, you don’t have to depend on external libraries.
But even if you do, a Python package manager (pip) makes things easier to import other
great packages from the Python package index (PyPi).
It consists of over 200,000 packages.
7. PORTABILITY
In many languages like C/C++, you need to change your code to run the program on
different platforms.
That is not the same with Python.
You only write once and run it anywhere.
However, you should be careful not to include any system-dependent features.

CONCLUSION
This article gives the best and smart way to visualize how COVID-19 has impacted various
states of INDIA. Since we are scrapping data from Wikipedia, we will be getting live data so
our application is not going to be static instead it changes every time when Wikipedia
updates their site on coronavirus.
Introduction to Tkinter
Graphical User Interface(GUI) is a form of user interface which allows users to interact
with computers through visual indicators using items such as icons, menus, windows, etc. It
has advantages over the Command Line Interface(CLI) where users interact with computers
by writing commands using keyboard only and whose usage is more difficult than GUI.

WHAT IS TKINTER?
Tkinter is the inbuilt python module that is used to create GUI applications. It is one of the
most commonly used modules for creating GUI applications in Python as it is simple and
easy to work with. You don’t need to worry about the installation of the Tkinter module
separately as it comes with Python already. It gives an object-oriented interface to the Tk
GUI toolkit.

Some other Python Libraries available for creating our own GUI applications are
 Kivy
 Python Qt
 wxPython
Among all Tkinter is most widely used

WHAT ARE WIDGETS?


Widgets in Tkinter are the elements of GUI application which provides various controls
(such as Labels, Buttons, Combo Boxes, Check Boxes, Menu Bars, RadioButtons and many
more) to users to interact with the application.

Widgets Description

Label It is used to display text or image on the screen


Button It is used to add buttons to your application

It is used to draw pictures and others layouts like


Canvas texts, graphics etc.

Combo It contains a down arrow to select from list of


Box available options

It displays a number of options to the user as


Check toggle buttons from which user can select any
Button number of options.

Radio It is used to implement one-of-many selection as


Button it allows only one option to be selected

Entry It is used to input single line text entry from user

It is used as container to hold and organize the


Frame widgets

It works same as that of label and refers to multi-


Message line and non-editable text

It is used to provide a graphical slider which


Scale allows to select any value from that scale

It is used to scroll down the contents. It provides


Scrollbar a slide controller.

SpinBox It is allows user to select from given set of values

It allows user to edit multiline text and format the


Text way it has to be displayed

It is used to create all kinds of menu used by an


Menu application

Example
from tkinter import * 
from tkinter.ttk import *
    
# writing code needs to
# create the main window of 
# the application creating 
# main window object named root
root = Tk()
  
# giving title to the main window
root.title("First Program")
  
# Label is what output will be 
# show on the window
label = Label(root, text ="Hello World !").pack()
  
# calling mainloop method which is used
# when your application is ready to run
# and it tells the code to keep displaying 
root.mainloop()

Output

HELLO WORLD
Python GUI – tkinter
 Difficulty Level : Medium

 Last Updated : 07 Jan, 2020


Python offers multiple options for developing GUI (Graphical User Interface). Out of all the
GUI methods, tkinter is the most commonly used method. It is a standard Python interface
to the Tk GUI toolkit shipped with Python. Python with tkinter is the fastest and easiest way
to create the GUI applications. Creating a GUI using tkinter is an easy task.

To create a tkinter app:


1. Importing the module – tkinter
2. Create the main window (container)
3. Add any number of widgets to the main window
4. Apply the event Trigger on the widgets.
Importing tkinter is same as importing any other module in the Python code. Note that the
name of the module in Python 2.x is ‘Tkinter’ and in Python 3.x it is ‘tkinter’.
import tkinter
There are two main methods used which the user needs to remember while creating the
Python application with GUI.
1. Tk(screenName=None,  baseName=None,  className=’Tk’,  useTk=1): To
create a main window, tkinter offers a method ‘Tk(screenName=None,  baseName=None,
className=’Tk’,  useTk=1)’. To change the name of the window, you can change the
className to the desired one. The basic code used to create the main window of the
application is:
m=tkinter.Tk() where m is the name of the main window object
2. mainloop(): There is a method known by the name mainloop() is used when your
application is ready to run. main loop() is an infinite loop used to run the application, wait
for an event to occur and process the event as long as the window is not closed.
m.mainloop()

import tkinter
m = tkinter.Tk()
'''
widgets are added here
'''
m.mainloop()

tkinter also offers access to the geometric configuration of the widgets which can organize
the widgets in the parent windows. There are mainly three geometry manager classes class.
1. pack() method: It organizes the widgets in blocks before placing in the parent
widget.
2. grid() method: It organizes the widgets in grid (table-like structure) before placing
in the parent widget.
3. place() method: It organizes the widgets by placing them on specific positions
directed by the programmer.
There are a number of widgets which you can put in your Tkinter application some majors
are:-
1.Button:To add a button in your application, this widget is used.
The general syntax is:
w=Button(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the Buttons. Number
of options can be passed as parameters separated by commas. Some of them are listed
below.

 active background: to set the background color when button is under the
cursor.

 active foreground: to set the foreground color when button is under the
cursor.

 bg: to set he normal background color.

 command: to call a function.

 font: to set the font on the button label.

 image: to set the image on the button.

 width: to set the width of the button.

 height: to set the height of the button.


import tkinter as tk
r = tk.Tk()
r.title('Counting Seconds')
button = tk.Button(r, text='Stop', width=25,
command=r.destroy)
button.pack()
r.mainloop()

Output:

2. Canvas: It is used to draw pictures and other complex layout like graphics, text and
widgets.
The general syntax is:
3. w = Canvas(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the widget. Number
of options can be passed as parameters separated by commas. Some of them are listed
below.

 bd: to set the border width in pixels.

 bg: to set the normal background color.

 cursor: to set the cursor used in the canvas.

 highlight color: to set the color shown in the focus highlight.

 width: to set the width of the widget.

 height: to set the height of the widget.

from tkinter import *


master = Tk()
w = Canvas(master, width=40, height=60)
w.pack()
canvas height=20
canvas_width=200
y = int(canvas_height / 2)
w.create_line(0, y, canvas_width, y )
mainloop()

4. Check Button: To select any number of options by displaying a number of options


to a user as toggle buttons. The general syntax is:
w = CheckButton(master, option=value)
There are number of options which are used to change the format of this widget. Number
of options can be passed as parameters separated by commas. Some of them are listed
below.

 Title: To set the title of the widget.

 Active background: to set the background color when widget is under the
cursor.

 Active foreground: to set the foreground color when widget is under the
cursor.

 bg: to set he normal background Steganography


Break
Secret Code:
Attach a File:nd color.

 command: to call a function.

 font: to set the font on the button label.

 image: to set the image on the widget.

from tkinter import *


master = Tk()
var1 = IntVar()
Check button(master, text='male',
variable=var1).grid(row=0, sticky=W)
var2 = IntVar()
Checkbutton(master, text='female',
variable=var2).grid(row=1, sticky=W)
mainloop()

5. Entry: It is used to input the single line text entry from the user.. For multi-line text
input, Text widget is used.
The general syntax is: w=Entry(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the widget. Number
of options can be passed as parameters separated by commas. Some of them are listed
below.

 bd: to set the border width in pixels.

 bg: to set the normal background color.

 cursor: to set the cursor used.

 command: to call a function.

 Highlight color: to set the color shown in the focus highlight.

 width: to set the width of the button.

 height: to set the height of the button.

from tkinter import *


master = Tk()
Label(master, text='First Name').grid(row=0)
Label(master, text='Last Name').grid(row=1)
e1 = Entry(master)
e2 = Entry(master)
e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
mainloop()

6. Frame: It acts as a container to hold the widgets. It is used for grouping and
organizing the widgets. The general syntax is:
7. w = Frame(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the widget. Number
of options can be passed as parameters separated by commas. Some of them are listed
below.

 Highlight color: To set the color of the focus highlight when widget has to
be focused.

 bd: to set the border width in pixels.

 bg: to set the normal background color.

 cursor: to set the cursor used.

 width: to set the width of the widget.

 height: to set the height of the widget.

from tkinter import *


  
root = Tk()
frame = Frame(root)
frame.pack()
bottomframe = Frame(root)
bottomframe.pack( side = BOTTOM )
redbutton = Button(frame, text = 'Red', fg ='red')
redbutton.pack( side = LEFT)
greenbutton = Button(frame, text = 'Brown', fg='brown')
greenbutton.pack( side = LEFT )
bluebutton = Button(frame, text ='Blue', fg ='blue')
bluebutton.pack( side = LEFT )
blackbutton = Button(bottomframe, text ='Black', fg
='black')
blackbutton.pack( side = BOTTOM)
root.mainloop()

8. Label: It refers to the display box where you can put any text or image which can be
updated any time as per the code.
The general syntax is:
9. w=Label(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the widget. Number
of options can be passed as parameters separated by commas. Some of them are listed
below.

 bg: to set he normal background color.

 bg to set he normal background color.

 command: to call a function.

 font: to set the font on the button label.

 image: to set the image on the button.

 width: to set the width of the button.

 height” to set the height of the button.

from tkinter import *


root = Tk()
w = Label(root, text='GeeksForGeeks.org!')
w.pack()
root.mainloop()
10. List box: It offers a list to the user from which the user can accept any number of
options.
The general syntax is:
11. w = Listbox(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the widget. Number
of options can be passed as parameters separated by commas. Some of them are listed
below.

 Highlight color: To set the color of the focus highlight when widget has to
be focused.

 bg: to set he normal background color.

 bd: to set the border width in pixels.

 font: to set the font on the button label.

 image: to set the image on the widget.

 width: to set the width of the widget.

 height: to set the height of the widget.

from tkinter import *


  
top = Tk()
Lb = Listbox(top)
Lb.insert(1, 'Python')
Lb.insert(2, 'Java')
Lb.insert(3, 'C++')
Lb.insert(4, 'Any other')
Lb.pack()
top.mainloop()

12. MenuButton: It is a part of top-down menu which stays on the window all the time.
Every menu button has its own functionality. The general syntax is:
13. w = MenuButton(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the widget. Number
of options can be passed as parameters separated by commas. Some of them are listed
below.

 Active background: To set the background when mouse is over the widget.

 Active foreground: To set the foreground when mouse is over the widget.

 bg: to set he normal background color.

 bd: to set the size of border around the indicator.

 cursor: To appear the cursor when the mouse over the menu button.

 image: to set the image on the widget.

 width: to set the width of the widget.

 height: to set the height of the widget.

 Highlight color: To set the color of the focus highlight when widget has to
be focused.

from tkinter import *


  
top = Tk()
mb =  Menubutton ( top, text = &quot;GfG&quot;)
mb.grid()
mb.menu  =  Menu ( mb, tearoff = 0 )
mb[&quot;menu&quot;]  =  mb.menu
cVar  = IntVar()
aVar = IntVar()
mb.menu.add_checkbutton ( label ='Contact', variable =
cVar )
mb.menu.add_checkbutton ( label = 'About', variable =
aVar )
mb.pack()
top.mainloop()

Output:
13.Menu: It is used to create all kinds of menus used by the application.
The general syntax is:
14. w = Menu(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of this widget. Number
of options can be passed as parameters separated by commas. Some of them are listed
below.

 title: To set the title of the widget.

 Active background: to set the background color when widget is under the
cursor.

 Active foreground: to set the foreground color when widget is under the
cursor.

 bg: to set he normal background color.

 command: to call a function.

 font: to set the font on the button label.

 image: to set the image on the widget.

from tkinter import *


      
root = Tk()
menu = Menu(root)
root.config(menu=menu)
filemenu = Menu(menu)
menu.add_cascade(label='File', menu=filemenu)
filemenu.add_command(label='New')
filemenu.add_command(label='Open...')
filemenu.add_separator()
filemenu.add_command(label='Exit', command=root.quit)
helpmenu = Menu(menu)
menu.add_cascade(label='Help', menu=helpmenu)
helpmenu.add_command(label='About')
mainloop()

Output:

15. Message: It refers to the multi-line and non-editable text. It works same as that of
Label.
The general syntax is:
16. w = Message(master, option=value)
17. master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the widget. Number
of options can be passed as parameters separated by commas. Some of them are listed
below.

 bd: to set the border around the indicator.

 bg: to set he normal background color.

 font: to set the font on the button label.


 image: to set the image on the widget.

 width: to set the width of the widget.

 height: to set the height of the widget.

from tkinter import *


main = Tk()
ourMessage ='This is our Message'
messageVar = Message(main, text = ourMessage)
messageVar.config(bg='lightgreen')
messageVar.pack( )
main.mainloop( )

Output:

18. RadioButton: It is used to offer multi-choice option to the user. It offers several
options to the user and the user has to choose one option.
The general syntax is:
19. w = RadioButton(master, option=value)
There are number of options which are used to change the format of this widget. Number
of options can be passed as parameters separated by commas. Some of them are listed
below.

 Active background: to set the background color when widget is under the
cursor.

 Active foreground: to set the foreground color when widget is under the
cursor.

 bg: to set he normal background color.

 command: to call a function.

 font: to set the font on the button label.

 image: to set the image on the widget.


 width: to set the width of the label in characters.

 height: to set the height of the label in characters.

from tkinter import *


root = Tk()
v = IntVar()
Radiobutton(root, text='GfG', variable=v,
value=1).pack(anchor=W)
Radiobutton(root, text='MIT', variable=v,
value=2).pack(anchor=W)
mainloop()

Output:

20. Scale: It is used to provide a graphical slider that allows to select any value from
that scale. The general syntax is:
21. w = Scale(master, option=value)
22. master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the widget. Number
of options can be passed as parameters separated by commas. Some of them are listed
below.

 cursor: To change the cursor pattern when the mouse is over the widget.

 activebackground: To set the background of the widget when mouse is over


the widget.

 bg: to set he normal background color.

 orient: Set it to HORIZONTAL or VERTICAL according to the


requirement.

 from_: To set the value of one end of the scale range.

 to: To set the value of the other end of the scale range.
 image: to set the image on the widget.

 width: to set the width of the widget.

from tkinter import *


master = Tk()
w = Scale(master, from_=0, to=42)
w.pack()
w = Scale(master, from_=0, to=200,
orient=HORIZONTAL)
w.pack()
mainloop()

Output:

23. Scrollbar: It refers to the slide controller which will be used to implement listed
widgets.
The general syntax is:
24. w = Scrollbar(master, option=value)
25. master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the widget. Number
of options can be passed as parameters separated by commas. Some of them are listed
below.

 width: to set the width of the widget.

 activebackground: To set the background when mouse is over the widget.


 bg: to set he normal background color.

 bd: to set the size of border around the indicator.

 cursor: To appear the cursor when the mouse over the menubutton.

from tkinter import *


root = Tk()
scrollbar = Scrollbar(root)
scrollbar.pack( side = RIGHT, fill = Y )
mylist = Listbox(root, yscrollcommand = scrollbar.set )
for line in range(100):
   mylist.insert(END, 'This is line number' + str(line))
mylist.pack( side = LEFT, fill = BOTH )
scrollbar.config( command = mylist.yview )
mainloop()

Output:

26. Text: To edit a multi-line text and format the way it has to be displayed.
The general syntax is:
27. w =Text(master, option=value)
There are number of options which are used to change the format of the text. Number of
options can be passed as parameters separated by commas. Some of them are listed
below.
 highlightcolor: To set the color of the focus highlight when widget has to be
focused.

 insertbackground: To set the background of the widget.

 bg: to set he normal background color.

 font: to set the font on the button label.

 image: to set the image on the widget.

 width: to set the width of the widget.

 height: to set the height of the widget.

from tkinter import *


root = Tk()
T = Text(root, height=2, width=30)
T.pack()
T.insert(END, 'GeeksforGeeks\nBEST WEBSITE\n')
mainloop()

Output:

28. TopLevel: This widget is directly controlled by the window manager. It don’t need
any parent window to work on.The general syntax is:
29. w = TopLevel(master, option=value)
There are number of options which are used to change the format of the widget. Number
of options can be passed as parameters separated by commas. Some of them are listed
below.

 bg: to set he normal background color.

 bd: to set the size of border around the indicator.

 cursor: To appear the cursor when the mouse over the menubutton.

 width: to set the width of the widget.


 height: to set the height of the widget.

from tkinter import *


root = Tk()
root.title('GfG')
top = Toplevel()
top.title('Python')
top.mainloop()

Output:

30. SpinBox: It is an entry of ‘Entry’ widget. Here, value can be input by selecting a
fixed value of numbers.The general syntax is:
31. w = SpinBox(master, option=value)
There are number of options which are used to change the format of the widget. Number
of options can be passed as parameters separated by commas. Some of them are listed
below.

 bg: to set he normal background color.

 bd: to set the size of border around the indicator.

 cursor: To appear the cursor when the mouse over the menubutton.
 command: To call a function.

 width: to set the width of the widget.

 activebackground: To set the background when mouse is over the widget.

 disabledbackground: To disable the background when mouse is over the


widget.

 from_: To set the value of one end of the range.

 to: To set the value of the other end of the range.

from tkinter import *


master = Tk()
w = Spinbox(master, from_ = 0, to = 10)
w.pack()
mainloop()

Output:

32. PannedWindowIt is a container widget which is used to handle number of panes


arranged in it. The general syntax is:
33. w = PannedWindow(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the widget. Number
of options can be passed as parameters separated by commas. Some of them are listed
below.

 bg: to set he normal background color.

 bd: to set the size of border around the indicator.

 cursor: To appear the cursor when the mouse over the menubutton.

 width: to set the width of the widget.

 height: to set the height of the widget.

from tkinter import *


m1 = PanedWindow()
m1.pack(fill = BOTH, expand = 1)
left = Entry(m1, bd = 5)
m1.add(left)
m2 = PanedWindow(m1, orient = VERTICAL)
m1.add(m2)
top = Scale( m2, orient = HORIZONTAL)
m2.add(top)
mainloop()

ADVANTAGES OF TKINTER

Advantages of Tkinter
 
Layered approach
The layered approach used in designing Tkinter gives Tkinter all of the
advantages of the TK library. Therefore, at the time of creation, Tkinter
inherited from the benefits of a GUI toolkit that had been given time to
mature. This makes early versions of Tkinter a lot more stable and
reliable than if it had been rewritten from scratch. Moreover, the
conversion from Tcl/Tk to Tkinter is really trivial, so that Tk
programmers can learn to use Tkinter very easily.

 
Accessibility
Learning Tkinter is very intuitive, and therefore quick and painless. The
Tkinter implementation hides the detailed and complicated calls in
simple, intuitive methods. This is a continuation of the Python way of
thinking, since the language excels at quickly building prototypes. It is
therefore expected that its preferred GUI library be implemented using
the same approach. For example, here is the code for a typical “Hello
world”-like application:
 
 
from Tkinter import *
root = Tk( )
root.title("A simple application")
root.mainloop( )
 
 
The first 2 lines allow to create a complete window. Compared to MFC
programming, it makes no doubt that Tkinter is simple to use. The third
line sets the caption of the window, and the fourth one makes it enter its
event loop.

 
Portability
Python scripts that use Tkinter do not require modifications to be ported
from one platform to the other. Tkinter is available for any platform that
Python is implemented for, namely Microsoft Windows, X Windows,
and Macintosh. This gives it a great advantage over most competing
libraries, which are often restricted to one or two platforms. Moreover,
Tkinter will provide the native look-and-feel of the specific platform it
runs on.
 

AVAILABILITY
Tkinter is now included in any Python distribution. Therefore, no
supplementary modules are required in order to run scripts using Tkinter

TKINTER CONCLUSION
Tkinter is excellent for small, quick GUI applications, and since it runs on more platforms
than any other Python GUI toolkit, it is a good choice where portability is the prime
concern.
Obviously we haven’t been able to give Tkinter the depth of discussion it warrants, but it’s
fair to say that almost anything that can be done using the C language and Tk can be done
using Python and Tkinter. One example is the Python megawidgets (PMW) package
mentioned previously; this is a pure Python package that creates an excellent widget set by
building on the core Tkinter widgets.
To learn more about any of the Tkinter topics discussed here, you may like to refer to the
following sources:
 The standard Python documentation is optionally installed with Python on Windows
and is also available online at http://www.python.org/doc.
 PythonWare and Fredrik Lundh provide excellent Tkinter resources, including
tutorials available at http://www.pythonware.com.
 Tcl and Tk are developed and supported by the Scriptics Corporation, which can be
found at http://www.scriptics.com. Tcl and Tk documentation is available
from http://www.scriptics.com/resource/doc/. O’Reilly has an excellent book on the
subject, Tcl/Tk in a Nutshell by Paul Raines and Jeff Trantor.
 Python megawidgets are available via http://pmw.sourceforge.net/.

KEEP YOUR EYE OUT FOR O’REILLY’S TKINTER P ROGRAMMING  BY FREDRIK


LUNDH.

MATPLOTLIB - INTRODUCTION
Matplotlib is one of the most popular Python packages used for data visualization. It is a
cross-platform library for making 2D plots from data in arrays. Matplotlib is written in
Python and makes use of NumPy, the numerical mathematics extension of Python. It
provides an object-oriented API that helps in embedding plots in applications using Python
GUI toolkits such as PyQt, WxPythonotTkinter. It can be used in Python and IPython
shells, Jupyter notebook and web application servers also.
Matplotlib has a procedural interface named the Pylab, which is designed to resemble
MATLAB, a proprietary programming language developed by MathWorks. Matplotlib
along with NumPy can be considered as the open source equivalent of MATLAB.
Matplotlib was originally written by John D. Hunter in 2003. The current stable version is
2.2.0 released in January 2018. Matplotlib and its dependency packages are available in the
form of wheel packages on the standard Python package repositories and can be installed
on Windows, Linux as well as MacOS systems using the pip package manager.
pip3 install matplotlib
Incase Python 2.7 or 3.4 versions are not installed for all users, the Microsoft Visual C++
2008 (64 bit or 32 bit forPython 2.7) or Microsoft Visual C++ 2010 (64 bit or 32 bit for
Python 3.4) redistributable packages need to be installed.
If you are using Python 2.7 on a Mac, execute the following command −

xcode-select –install

Upon execution of the above command, the subprocess32 - a dependency, may be


compiled.
On extremely old versions of Linux and Python 2.7, you may need to install the master
version of subprocess32.
Matplotlib requires a large number of dependencies −

 Python (>= 2.7 or >= 3.4)

 NumPy

 setuptools

 dateutil

 pyparsing

 libpng

 pytz

 FreeType

 cycler

 six
Optionally, you can also install a number of packages to enable better user interface
toolkits.

 tk

 PyQt4

 PyQt5

 pygtk
 wxpython

 pycairo

 Tornado
For better support of animation output format and image file formats, LaTeX, etc., you can
install the following −

 _mpeg/avconv

 ImageMagick

 Pillow (>=2.0)

 LaTeX and GhostScript (for rendering text with LaTeX).

 LaTeX and GhostScript (for rendering text with LaTeX).

MATPLOTLIB - SIMPLE PLOT


we will learn how to create a simple plot with Matplotlib.
We shall now display a simple line plot of angle in radians vs. its sine value in Matplotlib.
To begin with, the Pyplot module from Matplotlib package is imported, with an alias plt as
a matter of convention.

import matplotlib.pyplot as plt

Next we need an array of numbers to plot. Various array functions are defined in the
NumPy library which is imported with the np alias.

import numpy as np

We now obtain the ndarray object of angles between 0 and 2π using the arange() function
from the NumPy library.

x = np.arange(0, math.pi*2, 0.05)

The ndarray object serves as values on x axis of the graph. The corresponding sine values
of angles in x to be displayed on y axis are obtained by the following statement −

y = np.sin(x)

The values from two arrays are plotted using the plot() function.

plt.plot(x,y)

You can set the plot title, and labels for x and y axes.
You can set the plot title, and labels for x and y axes.
plt.xlabel("angle")
plt.ylabel("sine")
plt.title('sine wave')

The Plot viewer window is invoked by the show() function −

plt.show()

The complete program is as follows −

from matplotlib import pyplot as plt


import numpy as np
import math #needed for definition of pi
x = np.arange(0, math.pi*2, 0.05)
y = np.sin(x)
plt.plot(x,y)
plt.xlabel("angle")
plt.ylabel("sine")
plt.title('sine wave')
plt.show()

When the above line of code is executed, the following graph is displayed –
Now, use the Jupyter notebook with Matplotlib.
Launch the Jupyter notebook from Anaconda navigator or command line as described
earlier. In the input cell, enter import statements for Pyplot and NumPy −

from matplotlib import pyplot as plt


import numpy as np

To display plot outputs inside the notebook itself (and not in the separate viewer), enter the
following magic statement −

%matplotlib inline

Obtain x as the ndarray object containing angles in radians between 0 to 2π, and y as sine
value of each angle −

import math
x = np.arange(0, math.pi*2, 0.05)
y = np.sin(x)

Set labels for x and y axes as well as the plot title −

plt.xlabel("angle")
plt.ylabel("sine")
plt.title('sine wave')

Finally execute the plot() function to generate the sine wave display in the notebook (no
need to run the show() function) −

plt.plot(x,y)

After the execution of the final line of code, the following output is displayed –
While it is easy to quickly generate plots with the matplotlib.pyplot module, the use of
object-oriented approach is recommended as it gives more control and customization of
your plots. Most of the functions are also available in the matplotlib.axes.Axes class.
The main idea behind using the more formal object-oriented method is to create figure
objects and then just call methods or attributes off of that object. This approach helps better
in dealing with a canvas that has multiple plots on it.
In object-oriented interface, Pyplot is used only for a few functions such as figure creation,
and the user explicitly creates and keeps track of the figure and axes objects. At this level,
the user uses Pyplot to create figures, and through those figures, one or more axes objects
can be created. These axes objects are then used for most plotting actions.
THE MATPLOTLIB OBJECT HIERARCHY
One important big-picture matplotlib concept is its object hierarchy.
If you’ve worked through any introductory matplotlib tutorial, you’ve probably called
something like plt.plot([1, 2, 3]). This one-liner hides the fact that a plot is really a hierarchy
of nested Python objects. A “hierarchy” here means that there is a tree-like structure of
matplotlib objects underlying each plot.
A Figure object is the outermost container for a matplotlib graphic, which can contain
multiple Axes objects. One source of confusion is the name: an Axes actually translates into
what we think of as an individual plot or graph (rather than the plural of “axis,” as we might
expect).
You can think of the Figure object as a box-like container holding one or more Axes (actual
plots). Below the Axes in the hierarchy are smaller objects such as tick marks, individual
lines, legends, and text boxes. Almost every “element” of a chart is its own manipulable
Python object, all the way down to the ticks and labels:
Here’s an illustration of this hierarchy in action. Don’t worry if you’re not completely
familiar with this notation, which we’ll cover later on:
>>>
>>> fig, _ = plt.subplots()
>>> type(fig)
<class 'matplotlib.figure.Figure'>
Above, we created two variables with plt.subplots(). The first is a top-level Figure object.
The second is a “throwaway” variable that we don’t need just yet, denoted with an
underscore. Using attribute notation, it is easy to traverse down the figure hierarchy and see
the first tick of the y axis of the first Axes object:
>>>
>>> one_tick = fig.axes[0].yaxis.get_major_ticks()[0]
>>> type(one_tick)
<class 'matplotlib.axis.YTick'>
Above, fig (a Figure class instance) has multiple Axes (a list, for which we take the first
element). Each Axes has a yaxis and xaxis, each of which have a collection of “major ticks,”
and we grab the first one.
Matplotlib presents this as a figure anatomy, rather than an explicit hierarchy:

(In true matplotlib style, the figure above is created in the matplotlib docs here.)
STATEFUL VERSUS STATELESS APPROACHES
Alright, we need one more chunk of theory before we can get around to the shiny
visualizations: the difference between the stateful (state-based, state-machine) and stateless
(object-oriented, OO) interfaces.
Above, we used import matplotlib.pyplot as plt to import the pyplot module from matplotlib
and name it plt.
Almost all functions from pyplot, such as plt.plot(), are implicitly either referring to an
existing current Figure and current Axes, or creating them anew if none exist. Hidden in the
matplotlib docs is this helpful snippet:
“[With pyplot], simple functions are used to add plot elements (lines, images, text, etc.) to
the current axes in the current figure.” [emphasis added]
Hardcore ex-MATLAB users may choose to word this by saying something like,
“plt.plot() is a state-machine interface that implicitly tracks the current figure!” In English,
this means that:

 The stateful interface makes its calls with plt.plot() and other top-level pyplot
functions. There is only ever one Figure or Axes that you’re manipulating at a given
time, and you don’t need to explicitly refer to it.

 Modifying the underlying objects directly is the object-oriented approach. We


usually do this by calling methods of an Axes object, which is the object that
represents a plot itself.
The flow of this process, at a high level, looks like this:

Tying these together, most of the functions from pyplot also exist as methods of
the matplotlib.axes.Axes class.
This is easier to see by peeking under the hood. plt.plot() can be boiled down to five or so
lines of code:
>>>
# matplotlib/pyplot.py
>>> def plot(*args, **kwargs):
... """An abridged version of plt.plot()."""
... ax = plt.gca()
... return ax.plot(*args, **kwargs)

>>> def gca(**kwargs):


... """Get the current Axes of the current Figure."""
... return plt.gcf().gca(**kwargs)
Calling plt.plot() is just a convenient way to get the current Axes of the current Figure and
then call its plot() method. This is what is meant by the assertion that the stateful interface
always “implicitly tracks” the plot that it wants to reference.
pyplot is home to a batch of functions that are really just wrappers around matplotlib’s
object-oriented interface. For example, with plt.title(), there are corresponding setter and
getter methods within the OO approach, ax.set_title() and ax.get_title(). (Use of getters and
setters tends to be more popular in languages such as Java but is a key feature of
matplotlib’s OO approach.)
Calling plt.title() gets translated into this one line: gca().set_title(s, *args, **kwargs). Here’s
what that is doing:

 gca() grabs the current axis and returns it.

 set_title() is a setter method that sets the title for that Axes object. The
“convenience” here is that we didn’t need to specify any Axes object explicitly
with plt.title().
Similarly, if you take a few moments to look at the source for top-level functions
like plt.grid(), plt.legend(), and plt.ylabels(), you’ll notice that all of them follow the same
structure of delegating to the current Axes with gca() and then calling some method of the
current Axes. (This is the underlying object-oriented approach!)
UNDERSTANDING  PLT .SUBPLOTS () NOTATION
Alright, enough theory. Now, we’re ready to tie everything together and do some plotting.
From here on out, we’ll mostly rely on the stateless (object-oriented) approach, which is
more customizable and comes in handy as graphs become more complex.
The prescribed way to create a Figure with a single Axes under the OO approach is (not too
intuitively) with plt.subplots(). This is really the only time that the OO approach
uses pyplot, to create a Figure and Axes:
>>>
>>> fig, ax = plt.subplots()
Above, we took advantage of iterable unpacking to assign a separate variable to each of the
two results of plt.subplots(). Notice that we didn’t pass arguments to subplots() here. The
default call is subplots(nrows=1, ncols=1). Consequently, ax is a single AxesSubplot object:
>>>
>>> type(ax)
<class 'matplotlib.axes._subplots.AxesSubplot'>
We can call its instance methods to manipulate the plot similarly to how we call pyplots
functions. Let’s illustrate with a stacked area graph of three time series:
>>>
>>> rng = np.arange(50)
>>> rnd = np.random.randint(0, 10, size=(3, rng.size))
>>> yrs = 1950 + rng

>>> fig, ax = plt.subplots(figsize=(5, 3))


>>> ax.stackplot(yrs, rng + rnd, labels=['Eastasia', 'Eurasia', 'Oceania'])
>>> ax.set_title('Combined debt growth over time')
>>> ax.legend(loc='upper left')
>>> ax.set_ylabel('Total debt')
>>> ax.set_xlim(xmin=yrs[0], xmax=yrs[-1])
>>> fig.tight_layout()
Here’s what’s going on above:
 After creating three random time series, we defined one Figure (fig) containing one
Axes (a plot, ax).
 We call methods of ax directly to create a stacked area chart and to add a legend,
title, and y-axis label. Under the object-oriented approach, it’s clear that all of these
are attributes of ax.
 tight_layout() applies to the Figure object as a whole to clean up whitespace
padding.
Let’s look at an example with multiple subplots (Axes) within one Figure, plotting two
correlated arrays that are drawn from the discrete uniform distribution:
>>>
>>> x = np.random.randint(low=1, high=11, size=50)
>>> y = x + np.random.randint(1, 5, size=x.size)
>>> data = np.column_stack((x, y))

>>> fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2,


... figsize=(8, 4))

>>> ax1.scatter(x=x, y=y, marker='o', c='r', edgecolor='b')


>>> ax1.set_title('Scatter: $x$ versus $y$')
>>> ax1.set_xlabel('$x$')
>>> ax1.set_ylabel('$y$')

>>> ax2.hist(data, bins=np.arange(data.min(), data.max()),


... label=('x', 'y'))
>>> ax2.legend(loc=(0.65, 0.8))
>>> ax2.set_title('Frequencies of $x$ and $y$')
>>> ax2.yaxis.tick_right()

There’s a little bit more going on in this example:


 Because we’re creating a “1x2” Figure, the returned result of plt.subplots(1, 2) is
now a Figure object and a NumPy array of Axes objects. (You can inspect this
with fig, axs = plt.subplots(1, 2) and taking a look at axs.)
 We deal with ax1 and ax2 individually, which would be difficult to do with the
stateful approach. The final line is a good illustration of the object hierarchy, where
we are modifying the yaxis belonging to the second Axes, placing its ticks and
ticklabels to the right.
 Text inside dollar signs utilizes TeX markup to put variables in italics.
Remember that multiple Axes can be enclosed in or “belong to” a given figure. In the case
above, fig.axes gets us a list of all the Axes objects:
>>>
>>> (fig.axes[0] is ax1, fig.axes[1] is ax2)
(True, True)
(fig.axes is lowercase, not uppercase. There’s no denying the terminology is a bit
confusing.)
Taking this one step further, we could alternatively create a figure that holds a 2x2 grid
of Axes objects:
>>>
>>> fig, ax = plt.subplots(nrows=2, ncols=2, figsize=(7, 7))
Now, what is ax? It’s no longer a single Axes, but a two-dimensional NumPy array of them:
>>>
>>> type(ax)
numpy.ndarray

>>> ax
array([[<matplotlib.axes._subplots.AxesSubplot object at 0x1106daf98>,
<matplotlib.axes._subplots.AxesSubplot object at 0x113045c88>],
[<matplotlib.axes._subplots.AxesSubplot object at 0x11d573cf8>,
<matplotlib.axes._subplots.AxesSubplot object at 0x1130117f0>]],
dtype=object)

>>> ax.shape
(2, 2)
This is reaffirmed by the docstring:
“ax can be either a single matplotlib.axes.Axes object or an array of Axes objects if more
than one subplot was created.”
We now need to call plotting methods on each of these Axes (but not the NumPy array,
which is just a container in this case). A common way to address this is to use iterable
unpacking after flattening the array to be one-dimensional:
>>>
>>> fig, ax = plt.subplots(nrows=2, ncols=2, figsize=(7, 7))
>>> ax1, ax2, ax3, ax4 = ax.flatten() # flatten a 2d NumPy array to 1d
We could’ve also done this with ((ax1, ax2), (ax3, ax4)) = ax, but the first approach tends to
be more flexible.
To illustrate some more advanced subplot features, let’s pull some macroeconomic
California housing data extracted from a compressed tar archive, using io, tarfile,
and urllib from Python’s Standard Library.
>>>
>>> from io import BytesIO
>>> import tarfile
>>> from urllib.request import urlopen

>>> url = 'http://www.dcc.fc.up.pt/~ltorgo/Regression/cal_housing.tgz'


>>> b = BytesIO(urlopen(url).read())
>>> fpath = 'CaliforniaHousing/cal_housing.data'

>>> with tarfile.open(mode='r', fileobj=b) as archive:


... housing = np.loadtxt(archive.extractfile(fpath), delimiter=',')
The “response” variable y below, to use the statistical term, is an area’s average home
value. pop and age are the area’s population and average house age, respectively:
>>>
>>> y = housing[:, -1]
>>> pop, age = housing[:, [4, 7]].T
Next let’s define a “helper function” that places a text box inside of a plot and acts as an “in-
plot title”:
>>>
>>> def add_titlebox(ax, text):
... ax.text(.55, .8, text,
... horizontalalignment='center',
... transform=ax.transAxes,
... bbox=dict(facecolor='white', alpha=0.6),
... fontsize=12.5)
... return ax
We’re ready to do some plotting. Matplotlib’s gridspec module allows for more subplot
customization. pyplot’s subplot2grid() interacts with this module nicely. Let’s say we want
to create a layout like this:

Above, what we actually have is a 3x2 grid. ax1 is twice the height and width of ax2/ax3,
meaning that it takes up two columns and two rows.
The second argument to subplot2grid() is the (row, column) location of the Axes within the
grid:
>>>
>>> gridsize = (3, 2)
>>> fig = plt.figure(figsize=(12, 8))
>>> ax1 = plt.subplot2grid(gridsize, (0, 0), colspan=2, rowspan=2)
>>> ax2 = plt.subplot2grid(gridsize, (2, 0))
>>> ax3 = plt.subplot2grid(gridsize, (2, 1))
Now, we can proceed as normal, modifying each Axes individually:
>>>
>>> ax1.set_title('Home value as a function of home age & area population',
... fontsize=14)
>>> sctr = ax1.scatter(x=age, y=pop, c=y, cmap='RdYlGn')
>>> plt.colorbar(sctr, ax=ax1, format='$%d')
>>> ax1.set_yscale('log')
>>> ax2.hist(age, bins='auto')
>>> ax3.hist(pop, bins='auto', log=True)

>>> add_titlebox(ax2, 'Histogram: home age')


>>> add_titlebox(ax3, 'Histogram: area population (log scl.)')
Above, colorbar() (different from ColorMap earlier) gets called on the Figure directly,
rather than the Axes. Its first argument uses Matplotlib’s .scatter() and is the result
of ax1.scatter(), which functions as a mapping of y-values to a ColorMap.
Visually, there isn’t much differentiation in color (the y-variable) as we move up and down
the y-axis, indicating that home age seems to be a stronger determinant of house value.
The “Figures” Behind The Scenes
Each time you call plt.subplots() or the less frequently used plt.figure() (which creates a
Figure, with no Axes), you are creating a new Figure object that matplotlib sneakily keeps
around in memory. Earlier, we alluded to the concept of a current Figure and current Axes.
By default, these are the most recently created Figure and Axes, which we can show with
the built-in function id() to display the address of the object in memory:
>>>
>>> fig1, ax1 = plt.subplots()

>>> id(fig1)
4525567840

>>> id(plt.gcf()) # `fig1` is the current figure.


4525567840

>>> fig2, ax2 = plt.subplots()


>>> id(fig2) == id(plt.gcf()) # The current figure has changed to `fig2`.
True
(We could also use the built-in is operator here.)
After the above routine, the current figure is fig2, the most recently created figure.
However, both figures are still hanging around in memory, each with a corresponding ID
number (1-indexed, in MATLAB style):
>>>
>>> plt.get_fignums()
[1, 2]
A useful way to get all of the Figures themselves is with a mapping of plt.figure() to each of
these integers:
>>>
>>> def get_all_figures():
... return [plt.figure(i) for i in plt.get_fignums()]

>>> get_all_figures()
[<matplotlib.figure.Figure at 0x10dbeaf60>,
<matplotlib.figure.Figure at 0x1234cb6d8>]
Be cognizant of this if running a script where you’re creating a group of figures. You’ll
want to explicitly close each of them after use to avoid a MemoryError. By
itself, plt.close() closes the current figure, plt.close(num) closes the figure number num,
and plt.close('all') closes all the figure windows:
>>>
>>> plt.close('all')
>>> get_all_figures()
[]
A BURST OF COLOR: IMSHOW () AND  MATSHOW ()
While ax.plot() is one of the most common plotting methods on an Axes, there are a whole
host of others, as well. (We used ax.stackplot() above. You can find the complete list here.)
Methods that get heavy use are imshow() and matshow(), with the latter being a wrapper
around the former. These are useful anytime that a raw numerical array can be visualized as
a colored grid.
First, let’s create two distinct grids with some fancy NumPy indexing:
>>>
>>> x = np.diag(np.arange(2, 12))[::-1]
>>> x[np.diag_indices_from(x[::-1])] = np.arange(2, 12)
>>> x2 = np.arange(x.size).reshape(x.shape)
Next, we can map these to their image representations. In this specific case, we toggle “off”
all axis labels and ticks by using a dictionary comprehension and passing the result
to ax.tick_params():
>>>
>>> sides = ('left', 'right', 'top', 'bottom')
>>> nolabels = {s: False for s in sides}
>>> nolabels.update({'label%s' % s: False for s in sides})
>>> print(nolabels)
{'left': False, 'right': False, 'top': False, 'bottom': False, 'labelleft': False,
'labelright': False, 'labeltop': False, 'labelbottom': False}
Then, we can use a context manager to disable the grid, and call matshow() on each Axes.
Lastly, we need to put the colorbar in what is technically a new Axes within fig. For this, we
can use a bit of an esoteric function from deep within matplotlib:
>>>
>>> from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable

>>> with plt.rc_context(rc={'axes.grid': False}):


... fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 4))
... ax1.matshow(x)
... img2 = ax2.matshow(x2, cmap='RdYlGn_r')
... for ax in (ax1, ax2):
... ax.tick_params(axis='both', which='both', **nolabels)
... for i, j in zip(*x.nonzero()):
... ax1.text(j, i, x[i, j], color='white', ha='center', va='center')
...
... divider = make_axes_locatable(ax2)
... cax = divider.append_axes("right", size='5%', pad=0)
... plt.colorbar(img2, cax=cax, ax=[ax1, ax2])
... fig.suptitle('Heatmaps with `Axes.matshow`', fontsize=16)
Plotting in Pandas
The pandas library has become popular for not just for enabling powerful data analysis, but
also for its handy pre-canned plotting methods. Interestingly though, pandas plotting
methods are really just convenient wrappers around existing matplotlib calls.
That is, the plot() method on pandas’ Series and DataFrame is a wrapper around plt.plot().
One convenience provided, for example, is that if the DataFrame’s Index consists of
dates, gcf().autofmt_xdate() is called internally by pandas to get the current Figure and
nicely auto-format the x-axis.
In turn, remember that plt.plot() (the state-based approach) is implicitly aware of the current
Figure and current Axes, so pandas is following the state-based approach by extension.
We can prove this “chain” of function calls with a bit of introspection. First, let’s construct a
plain-vanilla pandas Series, assuming we’re starting out in a fresh interpreter session:
>>>
>>> import pandas as pd

>>> s = pd.Series(np.arange(5), index=list('abcde'))


>>> ax = s.plot()
>>> type(ax)
<matplotlib.axes._subplots.AxesSubplot at 0x121083eb8>

>>> id(plt.gca()) == id(ax)


True
This internal architecture is helpful to know when you are mixing pandas plotting methods
with traditional matplotlib calls, which is done below in plotting the moving average of a
widely watched financial time series. ma is a pandas Series for which we can
call ma.plot() (the pandas method), and then customize by retrieving the Axes that is created
by this call (plt.gca()), for matplotlib to reference:
>>>
>>> import pandas as pd
>>> import matplotlib.transforms as mtransforms

>>> url = 'https://fred.stlouisfed.org/graph/fredgraph.csv?id=VIXCLS'


>>> vix = pd.read_csv(url, index_col=0, parse_dates=True, na_values='.',
... infer_datetime_format=True,
... squeeze=True).dropna()
>>> ma = vix.rolling('90d').mean()
>>> state = pd.cut(ma, bins=[-np.inf, 14, 18, 24, np.inf],
... labels=range(4))

>>> cmap = plt.get_cmap('RdYlGn_r')


>>> ma.plot(color='black', linewidth=1.5, marker='', figsize=(8, 4),
... label='VIX 90d MA')
>>> ax = plt.gca() # Get the current Axes that ma.plot() references
>>> ax.set_xlabel('')
>>> ax.set_ylabel('90d moving average: CBOE VIX')
>>> ax.set_title('Volatility Regime State')
>>> ax.grid(False)
>>> ax.legend(loc='upper center')
>>> ax.set_xlim(xmin=ma.index[0], xmax=ma.index[-1])

>>> trans = mtransforms.blended_transform_factory(ax.transData, ax.transAxes)


>>> for i, color in enumerate(cmap([0.2, 0.4, 0.6, 0.8])):
... ax.fill_between(ma.index, 0, 1, where=state==i,
... facecolor=color, transform=trans)
>>> ax.axhline(vix.mean(), linestyle='dashed', color='xkcd:dark grey',
... alpha=0.6, label='Full-period mean', marker='')

There’s a lot happening above:


 ma is a 90-day moving average of the VIX Index, a measure of market expectations
of near-term stock volatility. state is a binning of the moving average into different
regime states. A high VIX is seen as signaling a heightened level of fear in the
marketplace.
 cmap is a ColorMap—a matplotlib object that is essentially a mapping of floats to
RGBA colors. Any colormap can be reversed by appending '_r', so 'RdYlGn_r' is the
reversed Red-Yellow-Green colormap. Matplotlib maintains a handy visual
reference guide to ColorMaps in its docs.
 The only real pandas call we’re making here is ma.plot(). This
calls plt.plot() internally, so to integrate the object-oriented approach, we need to get
an explicit reference to the current Axes with ax = plt.gca().
 The second chunk of code creates color-filled blocks that correspond to each bin
of state. cmap([0.2, 0.4, 0.6, 0.8]) says, “Get us an RGBA sequence for the colors at
the 20th, 40th, 60th, and 80th ‘percentile’ along the ColorMaps’
spectrum.” enumerate() is used because we want to map each RGBA color back to a
state.
Pandas also comes built-out with a smattering of more advanced plots (which could take up
an entire tutorial all on their own). However, all of these, like their simpler counterparts,
rely on matplotlib machinery internally.
WRAPPING UP
As shown by some of the examples above, there’s no getting around the fact that matplotlib
can be a technical, syntax-heavy library. Creating a production-ready chart sometimes
requires a half hour of Googling and combining a hodgepodge of lines in order to fine-tune
a plot.
However, understanding how matplotlib’s interfaces interact is an investment that can pay
off down the road. As Real Python’s own Dan Bader has advised, taking the time to dissect
code rather than resorting to the Stack Overflow “copy pasta” solution tends to be a smarter
long-term solution. Sticking to the object-oriented approach can save hours of frustration
when you want to take a plot from plain to a work of art.
MORE RESOURCES
From the matplotlib documentation:

 An index of matplotlib examples

 The usage FAQ

 The tutorials page, which is broken up into beginner, intermediate, and advanced


sections

 Lifecylcle of a plot, which touches on the object-oriented versus stateful approaches


Free Bonus: Click here to download 5 Python + Matplotlib examples with full source
code that you can use as a basis for making your own plots and graphics.
Third-party resources:

 DataCamp’s matplotlib cheat sheet

 PLOS Computational Biology: Ten Simple Rules for Better Figures

 Chapter 9 (Plotting & Visualization) of Wes McKinney’s Python for Data


Analysis, 2nd ed.

 Chaper 11 (Visualization with Matplotlib, Pandas, and Seaborn) of Ted


Petrou’s Pandas Cookbook

 Section 1.4 (Matplotlib: Plotting) of the SciPy Lecture Notes

 The xkcd color palette

 The matplotlib external resources page

 Matplotlib, Pylab, Pyplot, etc: What’s the difference between these and when to use
each? from queirozf.com

 The visualization page in the pandas documentation

Other plotting libraries:

 The seaborn library, built on top of matplotlib and designed for advanced statistical


graphics, which could take up an entire tutorial all on its own

 Datashader, a graphics library geared specifically towards large datasets

 A list of other third-party packages from the matplotlib documentation

APPENDIX A: CONFIGURATION AND STYLING


If you’ve been following along with this tutorial, it’s likely that the plots popping up on
your screen look different stylistically than the ones shown here.
Matplotlib offers two ways to configure style in a uniform way across different plots:
1. By customizing a matplotlibrc file
2. By changing your configuration parameters interactively, or from a .py script.
A matplotlibrc file (Option #1 above) is basically a text file specifying user-customized
settings that are remembered between Python sessions. On Mac OS X, this normally resides
at ~/.matplotlib/matplotlibrc.
Quick Tip: GitHub is a great place to keep configuration files. I keep mine here. Just make
sure that they don’t contain personally identifiable or private information, such as passwords
or SSH private keys!
Alternatively, you can change your configuration parameters interactively (Option #2
above). When you import matplotlib.pyplot as plt, you get access to an rcParams object that
resembles a Python dictionary of settings. All of the module objects starting with “rc” are a
means to interact with your plot styles and settings:
>>>
>>> [attr for attr in dir(plt) if attr.startswith('rc')]
['rc', 'rcParams', 'rcParamsDefault', 'rc_context', 'rcdefaults']
Of these:

 plt.rcdefaults() restores the rc parameters from matplotlib’s internal defaults, which


are listed at plt.rcParamsDefault. This will revert (overwrite) whatever you’ve
already customized in a matplotlibrc file.

 plt.rc() is used for setting parameters interactively.

 plt.rcParams is a (mutable) dictionary-like object that lets you manipulate settings


directly. If you have customized settings in a matplotlibrc file, these will be reflected
in this dictionary.
With plt.rc() and plt.rcParams, these two syntaxes are equivalent for adjusting settings:
>>>
>>> plt.rc('lines', linewidth=2, color='r') # Syntax 1

>>> plt.rcParams['lines.linewidth'] = 2 # Syntax 2


>>> plt.rcParams['lines.color'] = 'r'
Notably, the Figure class then uses some of these as its default arguments.
Relatedly, a style is just a predefined cluster of custom settings. To view available styles,
use:
>>>
>>> plt.style.available
['seaborn-dark', 'seaborn-darkgrid', 'seaborn-ticks', 'fivethirtyeight',
'seaborn-whitegrid', 'classic', '_classic_test', 'fast', 'seaborn-talk',
'seaborn-dark-palette', 'seaborn-bright', 'seaborn-pastel', 'grayscale',
'seaborn-notebook', 'ggplot', 'seaborn-colorblind', 'seaborn-muted',
'seaborn', 'Solarize_Light2', 'seaborn-paper', 'bmh', 'seaborn-white',
'dark_background', 'seaborn-poster', 'seaborn-deep']
To set a style, make this call:
>>>
>>> plt.style.use('fivethirtyeight')
Your plots will now take on a new look:

This full example is available here.


For inspiration, matplotlib keeps some style sheet displays for reference as well.
APPENDIX B: INTERACTIVE MODE
Behind the scenes, matplotlib also interacts with different backends. A backend is the
workhorse behind actually rendering a chart. (On the popular Anaconda distribution, for
instance, the default backend is Qt5Agg.) Some backends are interactive, meaning they are
dynamically updated and “pop up” to the user when changed.
While interactive mode is off by default, you can check its status
with plt.rcParams['interactive'] or plt.isinteractive(), and toggle it on and off
with plt.ion() and plt.ioff(), respectively:
>>>
>>> plt.rcParams['interactive'] # or: plt.isinteractive()
True
 
>>>
>>> plt.ioff()
>>> plt.rcParams['interactive']
False
In some code examples, you may notice the presence of plt.show() at the end of a chunk of
code. The main purpose of plt.show(), as the name implies, is to actually “show” (open) the
figure when you’re running with interactive mode turned off. In other words:

 If interactive mode is on, you don’t need plt.show(), and images will automatically
pop-up and be updated as you reference them.

 If interactive mode is off, you’ll need plt.show() to display a figure and plt.draw() to


update a plot.
Below, we make sure that interactive mode is off, which requires that we
call plt.show() after building the plot itself:
>>>
>>> plt.ioff()
>>> x = np.arange(-4, 5)
>>> y1 = x ** 2
>>> y2 = 10 / (x ** 2 + 1)
>>> fig, ax = plt.subplots()
>>> ax.plot(x, y1, 'rx', x, y2, 'b+', linestyle='solid')
>>> ax.fill_between(x, y1, y2, where=y2>y1, interpolate=True,
... color='green', alpha=0.3)
>>> lgnd = ax.legend(['y1', 'y2'], loc='upper center', shadow=True)
>>> lgnd.get_frame().set_facecolor('#ffb19a')
>>> plt.show()
MATPLOTLIB ADVANTAGES
It possesses the ability to work well with many operating systems and graphic
backends. It possesses high-quality graphics and plots to print and view for a
range of graphs such as histograms, bar charts, pie charts, scatter plots and heat
maps.

You might also like