Professional Documents
Culture Documents
WHAT IS PYTHON?
Python is a popular programming language. It was created by Guido van Rossum, and
released in 1991.
It is used for:
software development,
mathematics,
system scripting.
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.
WHY PYTHON?
Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
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.
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 was designed for readability, and has some similarities to the English
language with influence from mathematics.
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.
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 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
Widgets Description
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
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.
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.
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.
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.
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.
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.
Highlight color: To set the color of the focus highlight when widget has to
be focused.
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.
cursor: To appear the cursor when the mouse over the menu button.
Highlight color: To set the color of the focus highlight when widget has to
be focused.
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.
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.
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.
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.
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.
to: To set the value of the other end of the scale range.
image: to set the image on the widget.
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.
cursor: To appear the cursor when the mouse over the menubutton.
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.
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.
cursor: To appear the cursor when the mouse over the menubutton.
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.
cursor: To appear the cursor when the mouse over the menubutton.
command: To call a function.
Output:
cursor: To appear the cursor when the mouse over the menubutton.
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/.
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
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)
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.
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')
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 −
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)
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.
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)
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
>>> 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
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)
>>> id(fig1)
4525567840
>>> 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
An index of matplotlib examples
The usage FAQ
The xkcd color palette
Matplotlib, Pylab, Pyplot, etc: What’s the difference between these and when to use
each? from queirozf.com
If interactive mode is on, you don’t need plt.show(), and images will automatically
pop-up and be updated as you reference them.