100% found this document useful (5 votes)
808 views

Matplotlib Tutorial Learn Matplotlib by Examples B08XYJB9K3

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (5 votes)
808 views

Matplotlib Tutorial Learn Matplotlib by Examples B08XYJB9K3

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 204

MATPLOTLIB TUTORIAL

LEARN MATPLOTLIB BY
EXAMPLES.
Instructions are clear, concise and effective
Theory, Principles and Practice

Matplotlib is a Multiplatform visualization library for data that is built


on NumPy Arrays. This Library is designed to work with the broader SciPy
stack, which includes different modules of Python used for machine learning
and data science.
Matplotlib is the default (sort of) Python Data Visualization Package and is
being used extensively in the market for creating plots, charts, graphs for
datasets for better data analysis and visualization.
In this tutorial of Matplotlib, we will start with the basics of Matplotlib and
will cover all the different types of Plots available in Matplotlib.

-------------------------------------------------
TAB W. KEITH
Copyright © 2021 by Su Tran. All Right Reserved.
Table of Contents
1. Matplotlib Tutorial
2. Matplotlib Basics
3. Matplotlib Plots
4. Matplotlib 3D
5. Miscellaneous
MATPLOTLIB BASICS
INTRODUCTION TO
MATPLOTLIB
In this tutorial, we will cover the basic introduction of the Matplotlib library
in Python, important modules within Matplotlib, how to install Matplotlib
module and we will understand how this library is useful for data
visualization.
WHAT IS MATPLOTLIB?
Matplotlib is basically a Multiplatform visualization library for data that is
built on NumPy Arrays. This Library is designed to work with the broader
SciPy stack, which includes different modules of Python used for machine
learning and data science.
Matplotlib is the default(sort of) Python Data Visualization
Package.
As Matplotlib is a visualization library, these visualizations
allow us to represent huge amount of data in visual form like
charts and plots.
Matplotlib is useful in creating 2D plots from the data in
Arrays.
Matplotlib library is inspired by MATLAB programming
language and it also provides a similar interface like MATLAB
for graphics.
This library gets easily integrated with the Pandas
package which is used for data manipulation.
With the combination of Pandas and Matplotlib data
wrangling can be done along with the visualization and one
can get valuable insights out of the data.
Matplotlib library in Python is mainly known as Grammer of
Graphics and it is the most used library for creating charts
and plots in Python.
Matplotlib can be used with Jupyter Notebook, web server
Applications, and IPython shells.

It was written by John D. Hunter in 2003 and it was born with


its 0.1 version. Matplotlib received an early boost at the time when it was
adopted as the plotting package of choice by the Space Telescope Science
Institute.
The current stable version is 2.2.0 and it was released in 2018.
IMPORTANT MODULES IN
MATPLOTLIB
There are two important modules in Matplotlib Library and these are given
below:

1. pyplot
It is an important module in Matplotlib. In our further tutorials
in code examples, you will often see matplotlib.pyplot being used.
This module mainly provides us an interface that allows us to
automatically and implicitly create figures and their
axes to achieve the desired plot.
This is a great module when you quickly want to plot
something without the instantiation of any figure or any axes.

2. pylab
It is another important module of Matplotlib.
You need to install this module alongside the
matplotlib module.
The Module pylab helps to import NumPy and pyplot and it
is recommended when you need to work with arrays, perform
mathematical operations, and you want to access the plotting
features.
It is not recommended in case you are using IPython Kernel.
INSTALLING
MATPLOTLIB
The dependent packages of Matplotlib and the matplotlib itself are available
in the standard Python package repositories in the form of a wheel
package. Thus it can be easily installed on MacOS, Window, Linux, etc.
using the pip package manager.
Note: You must have Python installed on your machine, to install matplotlib
module. Here is our Python Installation Guide.
You just need to open your command prompt write the following given
command:
python -m pip install -U matplotlib
If you are using Jupyter Notebook, then it is important to note that Jupyter
Notebook comes with many preinstalled libraries like Numpy, Pandas,
Matplotlib, Scikit-Learn, so you don't have to worry about installing these
modules/libraries separately.
GENERAL CONCEPTS IN
MATPLOTLIB
In this tutorial, we will cover some general concepts in Matplotlib and some
tips for you to remember, with the help of which visualization becomes
easy.
As we know that Matplotlib is a powerful library which is used to visualize
data in form of plots. You will see in our tutorial that with the help of this
library one can create many types of plots like line, bar, histogram,
contour, scatter, violin, and many more. It is used for creating 2D plots of
Arrays.
Here are some general concepts which you must understand first before
moving on to the further topics. There are many parts of a figure created
using matplotlib and here we are going to discuss those parts, which are:
First of all, we have used the word "figure"; let us understand what is a figure
in Matplotlib?

1. Figure:
Figure is the canvas on which different plots are created. The Matplotlib
Figure is a canvas that contains one or more than one axes/plots.

2. Axis:
Axis in a Matplotlib figure is used for generating the graph limit and it is
basically like a number line. There can be an X axis, Y axis and Z axis for
plots upto 3 dimensional.

3. Axes:
Axes is generally considered as a plot. In the case of 3D, there are three-
axis objects but there are many axes in a figure.
4. Artist
Everything which can be seen on a figure is an Artist. Most of the artists are
tied with the axes. These are like text objects, collection objects and Line2D
objects, and many more.

Before diving into creating visualizations with the help of matplotlib; Let us
discuss a few things related to the Matplotlib Library:

1. Importing the Matplotlib Library


We will use some standard shorthand while importing the Matplotlib in our
code:
import matplotlib as mpl
import matplotlib.pyplot as plt

The plt interface mentioned above is used often in our further


tutorials.

2. Setting Styles
So, we will use the plt.style directive to choose appropriate aesthetic styles for
our figures.
Now, let us set the classic style, which ensures that the plots we create use
the classic Matplotlib style:
plt.style.use('classic')

3. Displaying the Plots


How the plots are displayed, depends on how you are using the Matplotlib
library.
There are three applicable contexts using which you can create plots using
Matplotlib: In a script, an IPython Notebook, or an IPython Shell.
PLOTTING FROM A
SCRIPT:
If you are using matplotlib from within a script, then plt.show() function is
your good friend. This function starts an event loop, then looks for all
currently active figure objects, and opens one or more interactive
windows that display your figure or figures.
Note: The plt.show() command should be used only once per Python
session and is most often seen at the very end of the script.
You cannot use multiple show() commands because if you will then it will lead
to unpredictable backend-dependent behavior. Thus it should mostly be
avoided.
Let us take an example of a file named myplt.py and the code inside the same is
given below:
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)


plt.plot(x, np.sin(x))
plt.plot(x, np.cos(x))
plt.show()
Run the above script in the command-line prompt, with the following
command: $ python myplot.py and it will result in a window opening with your
figure displayed.
Plotting from an IPython Shell
IPython is built to work well with Matplotlib if you specify the Matplotlib
mode. If you want to enable this mode, you can use the %matplotlib magic
command just after starting ipython:
%matplotlib
When you will run the above command, it will give:
Using matplotlib backend: Qt5Agg
After the above command, write the following code:
import matplotlib.pyplot as plt
Now any plt plot command will open a figure window, and then you can
further use commands that can be run to update the plot.
Some changes (like modifying properties of lines that are already drawn) will
not draw automatically; If you want to force an update then use plt.draw().
Using plt.show() in Matplotlib mode is not required.
Plotting from an IPython Notebook
Now IPython Notebook is basically a browser-based interactive data
analysis tool that is used to combine narrative, code, graphics, HTML
elements, and much more things into a single executable document.
If you want to plot interactively within an IPython notebook then use
the %matplotlib command and it will work in a similar way to the IPython shell.
In the IPython notebook, you also have the option of embedding graphics
directly in the notebook, with two possible options:
1. The command %matplotlib in the notebook will lead to
interactive plots embedded within the notebook.

2. The command %matplotlib inline will help to embed the static


images of your plot in the notebook

First of all, run the command given below:


%matplotlib inline
After you run this command (it needs to be done only once per
kernel/session), any cell within the notebook that creates a plot will embed a
PNG image of the resulting graphic.
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 100)
fig = plt.figure()
plt.plot(x, np.sin(x), '-')
plt.plot(x, np.cos(x), '--')
MATPLOTLIB IN JUPYTER
NOTEBOOK
In this tutorial, we will cover an introduction to the Jupyter Notebook in
which we will create visualizations using Matplotlib module and we will also
cover the main features of Jupyter Notebook.
Jupyter Notebook is an open-source web application with the help of which
one can create and share documents containing live python
code, visualizations, and code explanation.
Jupyter Notebook is used for data cleaning, data
visualization, machine learning, numerical simulation, and
many more such use cases.
Jupyter mainly stands for Julia, Python, and Ruby and also
initially Jupyter Notebook was developed for these three but
later on, it started supporting many other languages.
Ipython was developed in 2001 by Fernando Perez as a
command shell used for interactive computing in multiple
programming languages starting with Python. Then in 2014, a
spin-off project was announced by Fernando Perez which was
known as Project Jupyter.
nd as we know today, IPython continue to exist as a Python
shell and a kernel for Jupyter, while the notebook and other
language parts of IPython shifted under the Jupyter name.
Jupyter also added additional support for Julia, R, and Ruby.
FEATURES OF
JUPYTER(IPYTHON)
NOTEBOOK
Let us discuss the features of Jupyter Notebook after that we will discuss how
to launch it and use it with Matplotlib library:
Jupyter Notebook is a tool that is very flexible and very helpful
in sharing code with complete explanation, comments, images,
etc. together, which is very helpful if you are learning to code.
It is important to note that the Jupyter Notebook runs via
a web browser, and the notebook itself could be hosted on
your local machine or on a remote server.
With the help of the Jupyter Notebook, it becomes easy to view
code, execute the code, and display the results directly in
your web browser.
With the help of the Jupyter Notebook, you can share your code
with others. It allows interactive changes to the shared code
and data set.
Suppose there is a piece of code and you want to explain it's
working line-by-line, with live feedback, you could embed the
code simply in a Jupyter Notebook. The best thing is the code
will remain fully functional and you can add interactivity
along with the explanation, showing and telling at the same
time which is beneficial.

Let us start with the Jupyter notebook. Firstly you need to open Anaconda
navigator (that is a desktop graphical user interface included in Anaconda
allowing you to launch applications and easily manage the Conda packages,
environments, and channels without using command-line commands).
Now search Ananconda Navigator on your machine(you should install it in
advance if you want to use Jupyter Notebook
- https://docs.anaconda.com/anaconda/navigator/install/):

After opening the Anaconda Navigator you will see the installed
components in its distribution. Let us show you:
Now from here you just need to launch the Jupyter Notebook to start
working with Matpotlib. Just click on the launch and it will launch the
Jupyter Notebook.
As we have mentioned in the above points that Jupyter Notebook runs via a
Web Server.
After launching you will see this:

if you want to start by making a new notebook where you can perform your
task easily, you can easily do this just by clicking on the "New button" in the
"Files tab".
There you will see many options like a terminal, to make a regular text
file, to make a folder, last but not least you will also see the option to make
a Python 3 notebook. Let us show you a pictorial representation for your
clear understanding:
MATPLOTLIB PYPLOT API
In this tutorial, we will cover the Pyplot API in Matplotlib in detail, helping
you understand the use of Pyplot API in Matplotlib.
The matplotlib.pyplot is basically the collection of command style
functions that helps in making the Matplotlib work like MATLAB.
pyplotis mainly intended in Matplotlib for making interactive
plots and simple cases of programmatic plot generation.
Each function in pyplot makes some changes to the figure, for
example, there is a function to create a figure, for creating a
plotting area in a figure, for plotting some lines in the
plotting area, for decorating the plot with labels, etc.
NEW NOTEBOOK IN
JUPYTER NOTEBOOK
If you want to create a new notebook in Jupyter notebook where you desire to
store your work then we have shown you the option in our previous tutorial.
Now when you click on the "New" button then there you have options like
Python3, terminal, folder, etc.
Just click on Python3 and then there is a python Notebook for you that will
be saved with (.ipynb) extension.
Let us show you an image then it becomes clear to you:

Now in this notebook, you can run your commands, can draw any kind of
plot, histogram, or anything you want using Matplotlib, run it, and then save
it.
DIFFERENT TYPE OF
PLOTS
Let us now discuss different types of plots that can be visualized with the
help of Matplotlib library:
1. Bar
This will create a Bar plot.
2. hist
This will create a histogram.
3. hist2D
This will create a 2-dimensional histogram.
4. Pie
This will create a Pie chart.
5. Boxplot
This will create a Box and whisker plot.
6. Plot
This will help to plot lines.
7. Scatter
This will be used to draw a scatter plot of x vs. y.
8. Stackplot
This is used to draw a stacked area plot.
9. Quiver
This will help to plot a 2-dimensional field of arrows.
10. Stem
This will draw a stem plot.
11. Polar
This will draw a polar plot.
12. Step
This will draw a stem plot.
DIFFERENT TYPE OF
FIGURE FUNCTIONS
Let us discuss some functions related to figures in Matplotlib and these are
given below:
1. figure
This will create a new figure.
2. figtext
This is used to add text to the figure.
3. savefig
This is used to save the current figure.
4. show
This is used to display the figure.
5. close
This is used to close the window of the figure.
DIFFERENT TYPE OF
IMAGE FUNCTIONS
Let us discuss some functions related to images in Matplotlib:
Imread
This function is used to read an image from a file into an array
Imsave
This function is used to save an array in an image file.
Imshow
This is used to display the image on the axes.
DIFFERENT TYPES OF
AXIS FUNCTIONS
let us discuss some functions related to the axis in Matplotlib:
Axes
This is used to add axes to the figure.
Text
This is used to add the text to the Axes.
Title
This is used to set a title of the current axes
XLabel
This is used to Set the x-axis label of the current axis
YLabel
This is used to Set the y-axis label of the current axis
XTicks
This is used either to Get or set the x-limits of the current tick
locations and labels.
YTicks
This is used either to Get or set the y-limits of the current tick
locations and labels.
XScale
This is used to set the scaling of the x-axis.
YScale
This is used to set the scaling of the y-axis.
XLim
This is used to either Get or set the x-limits of the current axes
YLim
This is used to either Get or set the y-limits of the current axes
MATPLOTLIB SIMPLE
LINE PLOT
In this tutorial, we will cover the Simple Line Plots in Matplotlib.
The visualization of the single line function that is y=f(x) is simplest among
all. Let us take a look at creating simple plots of this type. In this tutorial, we
will cover the following simple line plots:
1. Straight Line for y=f(x) type
2. Graph for Sine function
3. Creating a single figure with Multiple Lines (Sine and Cose
function)
4. Curved Line

Now the first and foremost step is to set up the notebook for plotting
and importing those functions that we will use:

1. Importing Matplotlib

To import Matplotlib you just need to write the following command:


import matplotlib.pyplot as plt
where we will import matplotlib with an alias plt for the ease.

2. Importing Numpy
As we are going to plot numbers; so in order to plot numbers, we need an
array. In the Numpy module of Python, there are many functions for
creating array. So we will also import Numpy in our code. For ease, we
will import Numpy with an alias np.
The command for the same is given below:
import numpy as np
Graph for y=f(x) type in Matplotlib
Let us see the code snippet for the simplest equation:
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-1, 1, 50)
print(x)
y = 2*x + 1
plt.plot(x, y)
plt.show()
In the above code example, plot(x, y) function is mainly used to draw a straight
line. The output for this code snippet is given below:
GRAPH FOR A SINE WAVE
IN MATPLOTLIB
Now we are going to show you the visualization of Sine wave using
matplotlib. The code snippet for the same is given below:
EXPLANATION OF THE
CODE
Let us take a look at the brief explanation of the code:
1. The first step is to import the matplotlib.pyplot with an alias of plt.

2. The next step is to import Numpy with an alias of np in order


to use arrays and functions related to it.
3. Then we had imported the Math module for the mathematical
calculations required in the visualization.
4. Now the ndarray object of angles between 0 and 2(pie) is
obtained using the arange() function from the NumPy library.
5. In order to plot the values from the two arrays, we have used
the plot() function.
6. In the next two lines after it, we have set the x and y label of
the graph.
7. After that in the next line, we have set the title for the
graph with the help of title() function.
8. In order to display the graph we had used the show() function.
CREATING A SINGLE
FIGURE WITH MULTIPLE
LINES
If you want to create a single figure containing multiple lines then you just
simply need to call the plot function multiple times.
The code for the same is given below:
CREATING GRAPH WITH
CURVED LINES
To plot any line plot() method is used in Matplotlib. It is not necessary that it
should be a straight line always, as we just saw in the example above, how
we can plot a wave. We can also plot a curved line.
Let us take an example of a simple curve in Matplotlib:
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-1, 1, 50)
y = 2**x + 1

plt.plot(x, y)
plt.show()
The output for the same is given below:
In this tutorial, we have covered how to plot a straight line, to plot a
curved line, single sine wave and we had also covered plotting of multiple
lines.
This is all about plotting simple functions in Matplotlib. Now in our further
tutorials, we will cover more magical things with matplotlib. We will dive
into some more details about how to control the appearance of the axes and
lines.
MATPLOTLIB PYLAB
MODULE
In this tutorial, we will cover the Pylab module in Matplotlib.
This module mainly helps in bringing functions and classes from pyplot
and NumPy into the global namespace which then becomes easier for the
Matlab users.
This module provides a procedural interface to the Matplotlib
object-oriented plotting library.
This module gets installed alongside the Matplotlib;
Likewise, matplotlib.pyplot is a module in the Matplotlib
package.
It is a very convenient module as this module helps in
importing matplotlib.pyplot (for the plotting) and NumPy (for the
mathematics and working with arrays) in bulk in a single
namespace.

NOTE: Pylab conflicts with all sorts of built-in functions in Python, so it is


abandoned and is not used much.
SYNTAX TO IMPORT THE
PYLAB MODULE
The basic syntax to import the pylab module is given below:
from pylab import *
EXAMPLE USING PYLAB
MODULE:
To plot a curve, in this code example, we will use plot() function. You just
need to take same-length arrays in a pair. Let us take a look at the code for
the same:
from numpy import *
from pylab import *

x = linspace(-1, 4, 30)
y = x**2
plot(x, y)
show()
Now let us look at the output produced by this:
If there is a need to plot symbols rather than lines then you need to provide an
additional string argument in the plot() method.
The possible symbols and colors are as follows:
symbols: - , –, -., : , . , , , o , ^ , v , < , > , s , + , x , D , d , 1 , 2 , 3
,4,h,H,p,|,_
colors: b, g, r, c, m, y, k, w

Let us cover a live example for the same:


OVERLAYING PLOTS
USING PYLAB
The plots can be overlaid also. For which you need to use
multiple plot commands. The clf() function is used to clear the plot.
MATPLOTLIB OBJECT
ORIENTED INTERFACE
In this tutorial, we will cover the object-oriented interface in Matplotlib.
MATPLOTLIB
INTERFACES
There are two types of interfaces in Matplotlib for visualization and these are
given below:

1. MATLAB like interface Using Pyplot Interface

You can easily generate plots using pyplot module in the matplotlib library
just by importing matplotlib.pyplot module.
Also pyplot interface is a state-based interface.
The main quality of state-based interface is that it allows us
to add elements and/or modify the plot as we need, whenever
we need it.
The Pyplot interface shares a lot of similarities in syntax and
methodology with MATLAB.

There are some disadvantages too with this interface that's why Object
Oriented interface of Matplotlib come into play. The pyplot interface doesn't
really scale well when there is a need to make multiple plots or when we have
to make plots that require a lot of customization.

2. Object Oriented Interface in Matplotlib

To get more control over the plots created using matplotlib and for more
customization of plots we use object-oriented interface of matplotlib.
The Object-Oriented interface can be accessed so easily also
allow us to reuse objects and matplotlib internally used this
object-oriented interface.
The Object-Oriented approach is better at times when there
is a need to draw Multiple plots on the canvas.
The ides behind this interface is to create figure objects and
then just need to call methods or attributes off of that object.
In an object-oriented interface in matplotlib, Pyplot is used
only for a few functions like figure creation, and also the user
explicitly creates the figure and keeps track of the figure and
axes objects.
In this the user makes use of Pyplot to create figures, and with
the help of those figures, one or more axes objects can also be
created. You can use axes objects for most plotting actions.

Figure is mainly divided into two parts in matplotlib:

1. The Figure object:


The Figure object contains one or more axes objects.
Let us try to run some code:
import matplotlib.pyplot as plt
fig = plt.figure()
print(type(fig))
The output for the same will be as follows:
<class 'matplotlib.figure.Figure'>

2. The Axes object:


An axes represents a plot inside the figure
Let us try some code given below for the axes object:
from matplotlib import pyplot as plt
import numpy as np
import math
x = np.arange(0, math.pi*2, 0.05)
y = np.cos(x)
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.plot(x,y)
ax.set_title("cos wave")# used to set the title
ax.set_xlabel('angle')# used to set label for x-axis
ax.set_ylabel('cos') #used to set label for y-axis
plt.show() # used to display the plot

Description of the functions used in the above code:

1. plt.figure()
This function will create a figure instance that provides an empty canvas.

2. fig.add_axes([0,0,1,1])
The add_axes() method requires a list object of 4 elements that are
corresponding to the left, bottom, width, and height of the figure. It is
important to note that Each number must lie in between 0 and 1.
The output of the above code is as follows:
MATPLOTLIB FIGURE
CLASS
In this tutorial, we will cover the Figure class in the matplotlib library.
As we all know that matplotlib is a python library used to create
visualization which is also a numerical extension of Numpy library.
The matplotlib library contains a Figure class in the
matplotlib.figure module.
For all plotting elements figure class is mainly a top-level
container.
To instantiate the figure object you just need to call
the figure() function of the pyplot module ( It is a state-based
interface to matplotlib)
With the help of pyplot one can easily create histograms,
violin plot, contour plot, 3D plots, and many more.
We can also extend the Figure class and create a custom class
based on our requirements. (Python Inheritance)
FIGURE() FUNCTION
To create a new figure the figure() function of the pyplot module is used in the
matplotlib library.
Syntax:
The syntax to use this function is given below:
matplotlib.pyplot.figure(num, figsize, dpi, facecolor, edgecolor, frameon, FigureClass, clear, **kwargs)
Parameters:
Let us discuss the parameters of the figure() function:
1. num
The default value of this parameter is None. You can provide this
parameter and also the figure with this id already exists.
2. figsize(float, float)
This is used to indicate the width and height in pixels.
3. dpi
This parameter is used to indicate the resolution of the figure. The default
value is None.
4. facecolor
This parameter is used to indicate the background color.
5. edgecolor
This parameter is used to indicate the border color.
6. frameon
If you do not want to draw the frame of the figure, this option is used. The
default value of this parameter is true, which means by default the frame is
drawn.
7. FigureClass
This parameter mainly uses a custom Figure instance.
8. clear
The default value is false. If the value of this parameter is true and the figure
already exists, then it is cleared.

Returned Values:
This method returns the Figure instance which is also passed
to new_figure_manager in the backend.

Time for Example:


Let us discuss this function with the help of an example given below:

import matplotlib.pyplot as plt


from matplotlib.figure import Figure
class MyFigure(Figure):
def __init__(self, *args, figtitle='hi', **kwargs):

super().__init__(*args, **kwargs)
self.text(0.9, 0.98, figtitle, ha='center')

fig = plt.figure(FigureClass=MyFigure, figtitle='Example')


ax = fig.subplots()
ax.plot([1, 2, 4])
plt.show()

In the above code example, we have created a new class MyFigure inheriting
the original Figure class.
MATPLOTLIB AXES
CLASS
In this tutorial, we will cover the Axes class in the state-based
interface (pyplot module) in Matplotlib Library.
The image's region with the data space is commonly known as Axes object.
The flexible and basic unit for creating sub-plots is Axes.
With the help of axes, one can plot at any location in the
Figure; thus it provides you the creation of sub-plots in a
Flexible way.
Any Figure that is given may contain many axes, but a
given Axes object can only be in a figure.
In the case of two-dimension, the Axes contain two axis
objects and in the case of 3D, the Axes contain three-axis
objects.
To add an Axes object to the figure you just need to make a
call to add_axes() method.
The add_axes() method will return the axes object and adds axes at
the position rect [left, bottom, width, height] where all these
quantities are present in fractions of figure width and height.
AXES() FUNCTION
This function is mainly used to create an axes object with argument.
The argument is mainly a list of 4 elements [left, bottom, width, height]
Given below is a basic syntax of this function:
axes([left, bottom, width, height])
Let us take a look at the simplest example where we will use the axes()
function:
import matplotlib.pyplot as plt

fig = plt.figure()
#[left, bottom, width, height]
ax = plt.axes([0.2, 0.2, 0.9, 0.9])
The output for the same is as follows:

Explanation of the above example:


In the above code, axes([0.2, 0.2, 0.9, 0.9]), where the
first ‘0.2’ indicates the distance between the left side axis and
the border of the figure window that is 20%, of the total
width of the figure window.
The second ‘0.2’ is indicating the distance between the
bottom side axis and the border of the figure window that
is 20%, of the total height of the figure window.
Also, The first ‘0.9’ indicates that the axes width from left to
right is 90% and
the latter ‘0.9’ indicates the axes height from the bottom to
the top is 80%.
MEMBER FUNCTIONS IN
AXES CLASS
In the following section, we have member functions of axes class which are
used to add different elements to the plot:

1. ax.legend() Function
To add a legend to the plot figure the legend() method of axes class is used.
Here is the syntax:
ax.legend(handles, labels, loc)
Parameters:
This function takes three parameters:
1. The parameter labels is used to indicate a sequence of
strings and it mainly handles a sequence of Line2D.
2. The parameter loc can either be a string or an integer which
mainly specifies the legend location.

The Location The Location


string code

Best 0

upper right 1

upper left 2
lower left 3

lower right 4

Right 5

Center left 6

Center right 7

lower center 8

upper center 9

Center 10

Below we have a basic example where we will use legend() method:


import matplotlib.pyplot as plt

fig = plt.figure()
#[left, bottom, width, height]
ax = plt.axes([0.2, 0.2, 0.8, 0.8])

ax.legend(labels = ('label1', 'label2'), loc = 'center right')


The output for this code is as follows:
2. add_axes() Function
If there is a need then you can also add the axes object to the figure by just
by making a call to the add_axes() method (thus it is an alternative method).
This method will return the axes object and adds axes at position [left,
bottom, width, height] where all these quantities are in fractions of figure
width and height.
Here is the syntax:
add_axes([left, bottom, width, height])
let us cover an example using this method:
import matplotlib.pyplot as plt

fig = plt.figure()
#[left, bottom, width, height]
ax = fig.add_axes([1, 1, 1, 1])
The output for the above code example is as follows:
3. ax.plot() Function
It is the most basic method of the axes class that is used to plot values of
one array versus another as lines or markers.
This method can have an optional format string argument which is mainly
used to specify color, style and size of line and marker.

Using Color codes:

To specify colors we will use color codes:

Character Color

‘b’ Blue

‘g’ Green

‘r’ Red
‘b’ Blue

‘c’ Cyan

‘m’ Magenta

‘y’ Yellow

‘k’ Black

‘b’ Blue

‘w’ White

Using Marker codes:


To specify style of marker we will use this:

Character Description

‘.’ Point marker

‘o’ Circle marker

‘x’ X marker

Diamond
‘D’
marker
Hexagon
‘H’
marker

‘s’ Square marker

‘+’ Plus marker

Using Line styles:


Various line styles you can use are as follows:

Character Description

‘-‘ Solid line

‘—‘ Dashed line

‘-.’ Dash-dot line

‘:’ Dotted line

Hexagon
‘H’
marker

Here is the syntax:


plt.plot(X, Y, ‘CLM’)
Parameters:
X: This parameter denotes the x-axis.
Y: This parameter denotes the y-axis
CLM: stands for color, line, and Marker.
Let us cover an example for the above-explained function:
import matplotlib.pyplot as plt
import numpy as np

X = np.linspace(-np.pi, np.pi, 15)


C = np.cos(X)
S = np.sin(X)

# [left, bottom, width, height]


ax = plt.axes([0.1, 0.1, 0.8, 0.8])
ax1 = ax.plot(X, C, 'mx:')

ax2 = ax.plot(X, S, 'cD-')


ax.legend(labels = ('Cosine Function', 'Sine Function'),loc = 'upper left')

ax.set_title("Trigonometric Functions in Mathematics")


plt.show()
The output for the above code snippet is as shown below:
MATPLOTLIB
MULTIPLOTS WITH
SUBPLOTS() FUNCTION
In this tutorial, we will cover how to draw multiple plots in a single graph
in matplotlib.
You must be thinking, why would we want to have multiple plots in a single
graph. That will only lead to confusion and clutter. But if you need to either
do comparison between the two curves or if you want to show
some gradual changes in the plots(relative to each other), etc. in that case
multiple plots are useful.
In matplotlib, we can do this using Subplots.
The subplots() function is in the pyplot module of the matplotlib library and is
used for creating subplots/multiplots in an effective manner.
SUBPLOTS() FUNCTION
This function will create a figure and a set of subplots. It is basically a
wrapper function and which is used to create common layouts of
subplots(including the enclosing figure object) in a single call.
This function mainly returns a figure and an Axes object or
also an array of Axes objects.
If you use this function without any parameters then it will
return a Figure object and one Axes object.
SYNTAX OF SUPLOTS()
FUNCTION:
Given below is the syntax for using this function:
subplots(nrows, ncols, sharex, sharey, squeeze, subplot_kw, gridspec_kw, **fig_kw)
PARAMETERS:
Let us discuss the parameters used by this function:
nrows, ncols

The parameter nrows is used to indicate the number of rows and


the parameter ncols is used to indicate the number of columns of
the subplot grid. Both parameters have a default value as 1.
sharex, sharey

To control the sharing of properties among x (sharex) or among


y (sharey) axis these parameters are used.
squeeze

This optional parameter usually contains boolean values with the


default is True.
subplot_kw

This parameter is used to indicate the dict with keywords that are
passed to the add_subplot call which is used to create each subplot.
gridspec_kw

This parameter is used to indicate the dict with keywords passed to


the GridSpec constructor that is used to create the grid on which the
subplots are placed on
**fig_kw

All the additional keyword arguments passed to the .pyplot.figure call


are part of this parameter.
Now we will cover some examples so that all the concepts become clear for
you.

Example1: Plot with one Figure and an Axes

The code for this example is as follows:


import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2*np.pi, 400)


y = np.sin(x**2) + np.cos(x)
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_title('Simplest plot in the matplotlib')
Now its time to take a look the output for the code:

In this we have used the subplots() function, but we haven't added two plots to
the graph. So the subplots() function can be normally used to create a single
graph/plot as well.

Example 2: Stacked Plots

Let us cover an example for stacked plots. We will try to plot a sequence of
plots (i.e 2 here) just by stacking one over the other. As there is the stacking
of plots, so the number of rows (i.e nrows) will change, which means ncols stay
the same as 1. Also, Each subplot is identified by the index parameter.
The code snippet for this is as follows:
import numpy as np
import matplotlib.pyplot as plt
plt.figure(figsize=(6, 4))

def f(x):
return np.sin(x) - x * np.cos(x)
def fp(x):
""" The derivative function of f """
return x * np.sin(x)

X = np.arange(-5, 5.0, 0.05)


fig, ax = plt.subplots(2,
sharex='col', sharey='row')

ax[0].plot(X, f(X), 'bo', X, f(X), 'k')


ax[0].set(title=' function f')
ax[1].plot(X, fp(X), 'go', X, fp(X), 'k')
ax[1].set(xlabel='X Values', ylabel='Y Values',
title='Derivative Function of f')

plt.show()
Here is the output of the above code:
As ou can see in the output above that two plots are stacked one on top of the
other. The plot can be of some other type too. But when you want to do some
comparison between plots, this is a good approach.

Example 3: Plot within another Plot


For this code example. let's take a live example.
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
x = np.arange(0, 10, 0.01)
plt.plot(x, x-10)
plt.title("Bigger one ")
fig.add_subplot(2, 2, 4)
plt.plot(x, 10-x)
plt.title("Tiny one")
plt.show()
You can use the above terminal to run the other examples too and see the
output. Try making different plots too.
MATPLOTLIB SUBPLOTS()
FUNCTION
In this tutorial, we will cover the subplots() function in the state-based
interface Pyplot in the Matplotlib Library.
The subplots() function in the Matplotlib acts as a utility wrapper. This
function helps in creating common layouts of subplots and it also includes
the enclosing figure object, in a single call.
The main objective of this function is to create a figure with a
set of subplots.
Various kind of subplots supported by matplotlib is 2x1
vertical, 2x1 horizontal or a 2x2 grid.
MATPLOTLIB SUBPLOTS()
FUNCTION
The basic syntax to use this function is as follows:
matplotlib.pyplot.subplots(nrows, ncols, sharex, sharey, squeeze, subplot_kw, gridspec_kw, **fig_kw)
MATPLOTLIB SUBPLOTS()
FUNCTION PARAMETERS
Let us discuss the parameters used by this function:
nrows, ncols

The parameter nrows is used to indicate the number of rows and


the parameter ncols is used to indicate the number of columns of
the subplot grid.
sharex, sharey

To control the sharing of properties among x (sharex) or among


y (sharey) axis these parameters are used.
squeeze

This optional parameter usually contains boolean values with the


default is True.
subplot_kw

This parameter is used to indicate the dict with keywords that are
passed to the add_subplot call which is used to create each subplot.
gridspec_kw

This parameter is used to indicate the dict with keywords passed to


the GridSpec constructor that is used to create the grid on which the
subplots are placed on.
MATPLOTLIB SUBPLOTS()
FUNCTION RETURNED
VALUES
The values returned by these function are as follows:
fig: This method is used to return the figure layout.
ax: This method is mainly used to return the axes. It can be an
Axes object or an array of Axes objects.

Let us understand this method with the help of a few examples:


EXAMPLE 1:
With the given below code snippet, we will create a figure having 2 rows
and 2 columns of subplots.
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(2, 2)
x = np.linspace(0, 8, 1000)

ax[0, 0].plot(x, np.sin(x), 'c') #row=0, col=0


ax[1, 0].plot(x, np.tan(x), 'r') #row=1, col=0
ax[0, 1].plot(range(50), 'y') #row=0, col=1
ax[1, 1].plot(x, np.cos(x), 'k') #row=1, col=1
fig.show()
The output for the above code is as follows:

Let us cover a live example to understand this function in more detail.


EXAMPLE2
Let us understand the code of the live example which is given below in which
we have plotted two sub plots.
from pylab import *
t = arange(0.0, 20.0, 1)
s = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
subplot(1,2,1)
xticks([]), yticks([])
title('subplot(1,2,1)')
plot(t,s)
subplot(1,2,2)
xticks([]), yticks([])
title('subplot(1,2,2)')
plot(t,s,'g-')
show()
MATPLOTLIB
SUBPLOT2GRID()
FUNCTION
In this tutorial, we will cover subplot2grid() function in state-based interface i.e
Pyplot in the Matplotlib library
This function is used to provide additional flexibility in creating axes
object at a particular specified location inside a grid.
For the spanning of the axes object across multiple rows or
columns, we will use this method.
subplot2grid() function is also termed as a sub-figure layout
manager.
In short terms, we will use this function to create multiple
charts within the same figure.
MATPLOTLIB
SUBPLOT2GRID()
FUNCTION
The subplot2grid() function or the matplotlib.pyplot.subplot2grid function can be used
easily to create multiple charts within same figure, here is the syntax for it:
matplotlib.pyplot.subplot2grid(shape, location, rowspan, colspan)
MATPLOTLIB
SUBPLOT2GRID()
PARAMETERS:
Let us discuss the parameters used by this function:
shape

The shape parameter is used to indicate the shape of the grid to be


plotted inside the graph. It is a mandatory argument for this
method.
It is generally passed as a list or tuple of two numbers that are
mainly responsible for the layout of the grid and the first
number indicates the number of rows while the second
number indicates the number of columns.
location

This parameter is also a mandatory parameter taken by this


function. This method is similar to the shape argument and is also
generally passed in as a list or tuple of two numbers. It is used for
specifying the row and column number where the sub-plot will
be placed. One thing to note is that the indexes always start from
0.
So (0, 0) is the cell in the first row and the first column of the grid.
rowspan

After setting the grid layout and the starting index using the
location(loc) parameter, one can also expand the selection to take
up more rows with this argument if needed. This is an optional
parameter having 1 as default value.
colspan

This parameter is similar to rowspan parameter and it is used in


order to expand the selection to take up more columns. This is
also an optional parameter having 1 as the default value.
EXAMPLE:
Let us draw a 3x3 grid of the figure object that is filled with axes objects of
varying sizes in a row and column spans. The code snippet for the same is
given below:
import matplotlib.pyplot as plt

def annotate_axes(fig):
for i, ax in enumerate(fig.axes):
ax.text(0.5, 0.5, "block%d" % (i+1), va="center", ha="center")
ax.tick_params(labelbottom=False, labelleft=False)

fig = plt.figure()
ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3)
ax2 = plt.subplot2grid((3, 3), (1, 0), colspan=2)
ax3 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)
ax4 = plt.subplot2grid((3, 3), (2, 0))
ax5 = plt.subplot2grid((3, 3), (2, 1))

annotate_axes(fig)
plt.show()
The output of the above code snippet is as follows:
MATPLOTLIB GRIDS
In this tutorial, we will cover what are grids in a figure, and how it be
customized using the grid() function in the Matplotlib.
WHAT ARE GRIDS?
In any chart or graphical representation of any set of data, grids are made so
that you can better understand the whole graph/chart and relate the points on
the plot with the scale values, as there are grid lines in the background. Grid
makes the inner part of a graph/chart basically made up of intersecting lines
either straight (vertical, horizontal, and angular) or curved lines that are
mainly used to represent the data.
With the help of grids in matplotlib you can gain a
better understanding of graphs.
You can easily get a reference for the data points.
matplotlib.pyplot.grid() is a function that is used to create grids
easily and you can also customize as there are many options
available.
MATPLOTLIB GRID()
FUNCTION
This function is basically used to create the grid.
In axes object the grid() function is used to set the visibility of
the grid inside the figure. It can be either on or off.
The linestyle and linewidth properties can be set in the grid()
function.
You can customize the grid according as per your requirements
as there are many available options.
MATPLOTLIB GRID()
SYNTAX
Below we have the basic syntax to use the
function matplotlib.pyplot.grid() function:
matplotlib.pyplot.grid(b, which, axis, **kwargs)
Let us discuss about the parameters used in this function:
b

This parameter indicates a bool value which is used to specify


whether to show grid-lines or not. The default value of this
parameter is True.
which

This parameter is used to indicate the grid lines on which there is a


need to apply the change. There are three for values for
this: major, minor, or both.
axis

This parameter is used to denote the axis on which there is a need to


apply changes. The values for this are x, y, or both.
**kwargs

This parameter is used to indicate the optional line properties.


EXAMPLE1
Let us take a look at an example where we will create a grid in the graph:
import numpy as np
import matplotlib.pyplot as plt

t = np.arange(0.0, 1.0 + 0.01, 0.01)


s = np.cos(2 * 2*np.pi * t)
t[41:60] = np.nan
plt.subplot(2, 1, 1)
plt.plot(t, s, '-', lw=2)

plt.xlabel('time (s)')
plt.ylabel('voltage (mV)')
plt.title('A sine wave having gap of NaNs between 0.4 and 0.6')
plt.grid(True)
plt.subplot(2, 1, 2)
t[0] = np.nan
t[-1] = np.nan
plt.plot(t, s, '-', lw=2)
plt.title('Graph with NaN in first and last point')

plt.xlabel('time (s)')
plt.ylabel('more nans')
plt.grid(True)
plt.tight_layout()
plt.show()
The output for the above code snippet is as follows:
In the function above, all we have done is added the plt.grid(True), which shows
the grid in the final graph.
EXAMPLE 2
Now in the example given below, we will show you how to use various
options to customize the graph:
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2 * np.pi, 400)


y = np.sin(x ** 2)
plt.plot(x, y, 'orange')

plt.title("Customized Plots")
# customize grids
plt.grid(True, color = "black", linewidth = "1.4", linestyle = "-.")

plt.show()
The output for the above code will be as follows:

In the above figure, you can see the grid lines are made of -. which we have
specified using the linestyle parameter, the width of line is specified
as 1.4 which controls the width of the line. We have also specified the plot
color to be orange, which we can see in the output.
FORMATTING THE AXES
IN MATPLOTLIB
In this tutorial, we will cover how to format the Axes in the Matplotlib. Let
us first learn what is Axes in Matplotlib.
MATPLOTLIB AXES
The region of the image that contains the data space is mainly known as
Axes.
The Axes in the Matplotlib mainly contains two-axis( in case
of 2D objects) or three-axis(in case of 3D objects)which then
take care of the data limits.

Let us show you different parts of the figure that contains the graph:

You can change different aspects of the Axes according to your requirements
and the further sections of this tutorial we will learn how to do that.

1. Labelling of x-axis and y-axis

In this section we will cover how to label x and y axis in Matplotlib.


Given below is the syntax for labelling of x-axis and y-axis:

For x-axis:
Axes.set_xlabel(self, xlabel, fontdict=None, labelpad=None, \*\*kwargs)

For y-axis:
Axes.set_ylabel(self, ylabel, fontdict=None, labelpad=None, \*\*kwargs)
In this way with the help of above two functions you can easily name the x-
axis and y-axis.

Labelling x-axis and y-axis Example:

Now let us take a look at an example where we will make use of above two
functions in order to name x-axis and y-axis.
import matplotlib.pyplot as plt
import numpy as np
a = [1, 2, 7, 4, 12]
b = [11, 3, 7, 5, 2]

# below function will create a figure and axes


fig,ax = plt.subplots()
# setting title to graph
ax.set_title('Sample')

# label x-axis and y-axis


ax.set_ylabel('Vertical / yaxis')
ax.set_xlabel('Horizontal / xaxis')
# function to plot and show graph
ax.plot(a, b)
plt.show()
And the output:
2. Set Limit of x-axis and y-axis

In this section we will cover how to set the limit for x and y axis in
Matplotlib.
Given below is the syntax for labelling of x-axis and y-axis:

For x-axis:
Axes.set_xlim(self, left=None, right=None, emit=True, auto=False, \*, xmin=None, xmax=None)
Function Parameters:
left, right

These two parameters are in float and are optional


The left xlim that is starting point and right xlim that is ending
point in data coordinates. If you will pass None to it then it will leave
the limit unchanged.
auto

This parameter is in bool and it is optional too.


If you want to turn on the autoscaling of the x-axis, then the value
of this parameter should be true, and false value of this parameter
means turns off the autoscaling (which is the default action), and
the None value leaves it unchanged.
xmin, xmax

These two parameters are equivalent to left and right respectively,


and it causes an error if you will pass value to both xmin and left
or xmax and right.
Returned Values:
This will return right and left value that is (float, float)

For y-axis:
Axes.set_ylim(self, bottom=None, top=None, emit=True, auto=False, \*, ymin=None, ymax=None)
Function Parameters:
bottom and top

These two parameters are in float and are optional.


The bottom ylim(that is starting point) and top ylim that is ending
point in data coordinates. If you will pass None to it then it will leave
the limit unchange
auto

This parameter is in bool and it is optional.


If you want to turn on the autoscaling of the y-axis then the value
of this parameter should be true and the false value of this
parameter means turns off autoscaling and the None value leaves it
unchanged.
ymin, ymax

These two parameters are equivalent to bottom and


top respectively, and it causes an error if you will pass value to both
xmin and bottom or xmax and top.
Returned Values:
This will return bottom and left value that is (float, float)

Set Limit for x-axis and y-axis Example:

Now let us take a look at an example where we will make use of above two
functions in order to set the limit of x-axis and y-axis.
import matplotlib.pyplot as plt
import numpy as np
x = [2, 4, 9, 5, 10]
y = [10, 4, 7, 1, 2]

# create a figure and axes


fig, ax = plt.subplots()
ax.set_title('Example Graph')

ax.set_ylabel('y_axis')
ax.set_xlabel('x_axis')
# set x, y-axis limits
ax.set_xlim(0, 10)
ax.set_ylim(0, 10)

# function to plot and show graph


ax.plot(x, y)
plt.show()
Here is the output:
3. Major and Minor Ticks

In Matplotlib, the Ticks are basically the values of the x and y axis.
Basically Minor Ticks are divisions of major ticks (like centimeter and
millimeter, where CM can be major tick and MM can be minor tick).
We have two classes Locator and Formatter for controlling the ticks:
The Locator class determine where the ticks will be shown.
While the Formatter class mainly controls the formatting of the
ticks.

You must need to import these two classes from matplotlib:


1. MultipleLocator()
This function helps to place ticks on multiples of some base.

2. FormatStrFormatter
It will use a string format like for example: '%d' or '%1.2f' or '%1.1f cm' in
order to format the tick labels.
Note: It is important to note here that Minor ticks are by default OFF and
they can be turned ON without labels and just by setting the minor locator
while minor tick labels can be turned ON with the help of minor formatter.

Major and Minor Ticks Example:


Let's see an example,
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import (MultipleLocator, FormatStrFormatter,
AutoMinorLocator)

t = np.arange(0.0, 100.0, 0.1)


s = np.sin(0.1 * np.pi * t) * np.exp(-t * 0.01)
fig, ax = plt.subplots()
ax.plot(t, s)

# Make a plot with major ticks that are multiples of 10 and minor ticks that
# are multiples of 5. Label major ticks with '%d' formatting but don't label
# minor ticks.
ax.xaxis.set_major_locator(MultipleLocator(10))
ax.xaxis.set_major_formatter(FormatStrFormatter('%d'))
# For the minor ticks, use no labels; default NullFormatter.
ax.xaxis.set_minor_locator(MultipleLocator(5))

plt.show()
Here is the output:
SETTING LIMITS FOR
AXIS IN MATPLOTLIB
In this tutorial, we will cover how to set up the limits in the matplotlib for the
X axis and Y axis values.
The Matplotlib Library automatically sets the minimum and maximum
values of variables to be displayed along x, y (and z-axis in case of the 3D
plot) axis of a plot.
But you can also set the limits explicitly.
There are two functions available by which you can easily set
the limits explicitly:
set_xlim() for setting the limit of the x-axis
set_ylim() for setting the limit of the y-axis

Now we will cover two examples, in the first one, the limits are automatically
set up by the matplotlib library while in our second example we will set up
the limits explicitly.
MATPLOTLIB DEFAULT
LIMITS:
In the example given below the limits are set automatically by the matplotlib
library.
import matplotlib.pyplot as plt

fig = plt.figure()
a1 = fig.add_axes([0,0,1,1])
import numpy as np

x = np.arange(1,10)
a1.plot(x, np.log(x))
a1.set_title('Logarithm')
plt.show()
Here is the output:
SETTING CUSTOM LIMITS
IN MATPLOTLIB
Now in this example, we will set the limits explicitly using the functions
discussed above. Let us take a look at the code:
import matplotlib.pyplot as plt

fig = plt.figure()
a1 = fig.add_axes([1,1,1,1])
import numpy as np

x = np.arange(1, 100)
a1.plot(x, np.exp(x),'c')
a1.set_title('Exponent')
# to set the y axis limits
a1.set_ylim(0, 10000)
# to set the x axis limits
a1.set_xlim(0, 10)

plt.show()
Here is the output:
SETTING TICKS AND TICK
LABELS IN MATPLOTLIB
In this tutorial, we will learn how to set ticks on the axis and specify custom
tick labels to make your matplotlib graph more readable and intuitive.
In Matplotlib library the Ticks are the markers that are used to denote the
data points on the axis.
It is important to note that in the matplotlib library the task
of spacing points on the axis is done automatically.
The default tick locators and formatters in matplotlib are also
good and are sufficient for most of the use-cases.
This task can be done explicitly with the help of two
functions: set_xticks() and set_yticks()
Both these functions will take a list object as its arguments. The
elements that are present in the list denote the positions and the
values that will be shown on these tick positions is set using
the set_xticklables() and set_yticklabels() functions.

For Example:
ax.set_xticks([2,4,6,8,12])
The above code will mark the data points at the given positions with ticks.
Then to set the labels corresponding to tick marks, we use the set_xticklabels()
and set_yticklabels() functions respectively.
ax.set_xlabels(['two', 'four', 'six', 'eight', 'twelve'])
Now with the help of the above command, It will display the text labels just
below the markers on the x-axis.
CUSTOM TICKS AND TICK
LABELS
Now let us take a look at an example of setting ticks and tick labels in
Matplotlib Library:
import matplotlib.pyplot as plt
import numpy as np
import math

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


fig = plt.figure()
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
y = np.cos(x)
ax.plot(x, y)
# this will label the x axis
ax.set_xlabel('angles')
# setting title of plot
ax.set_title('cos')
# set the tick marks for x axis
ax.set_xticks([0,2,4,6])
# provide name to the x axis tick marks
ax.set_xticklabels(['zero','two','four','six'])
ax.set_yticks([-1,0,1])

plt.show()
Here is the output:
In the above code, you must have noticed the function set_xlabel(), this function
is used to specify a label for the X axis, in our case we are showing angles on
x axis, hence the name angles.
Then we have specified the tick marks explicitly and have also provided
labels for the tick marks.
This is a good technique to customize your graphs completely.
MATPLOTLIB TWIN AXES
In this tutorial, we will cover the concept of twin/dual axes in matplotlib.
In the axes class, there are many figure elements present like Axis, Tick,
Line2D, Text, Polygon, etc., which are used to set the coordinate system.
When we say twin axes, it means a figure can have dual x or y-axes. Also,
when plotting curves with different units together, then also twin axes is
very useful.
In Matplotlib this task is supported with the twinx and twiny functions.
MATPLOTLIB TWINX()
AND TWINY() FUNCTION
In the Axes Module, there is a function named Axes.twinx() function which is
used to create a twin Axes that are sharing the x-axis. Similarly, the
function twiny() is used to create a second x axis in your figure, which means
twin axes sharing the y-axis.
The syntax to use this function is as follows:
# for x axis
Axes.twinx(self)
# for y axis
Axes.twiny(self)
Note: This function does not take any parameters, if you will do so then it
will raise errors.
The values returned by this method are as follows:
ax_twin: which indicates that it will return the newly created Axes instance.
Now it's time to dive into some examples using this function,
EXAMPLE 1:
Here is an example of twin axes plot in matplotlib:
import numpy as np
import matplotlib.pyplot as plt

t = np.arange(0.01, 10.0, 0.001)


data1 = np.exp(t)
data2 = np.cos(0.4 * np.pi * t)
fig, ax1 = plt.subplots()

color = 'tab:orange'
ax1.set_xlabel('time (s)')
ax1.set_ylabel('exp', color = color)
ax1.plot(t, data1, color = color)
ax1.tick_params(axis ='y', labelcolor = color)
ax2 = ax1.twinx()

color = 'tab:cyan'
ax2.set_ylabel('cos', color = color)
ax2.plot(t, data2, color = color)
ax2.tick_params(axis ='y', labelcolor = color)
fig.suptitle('matplotlib.axes.Axes.twinx()function Example\n\n', fontweight ="bold")

plt.show()
The output for the above code is as follows:
In the above code, we used the twinx() function and we got twin axes sharing
the x-axis.
MATPLOTLIB PLOTS
MATPLOTLIB BAR PLOT -
BAR() FUNCTION
In this tutorial, we will cover the bar plot in Matplotlib and how to create it.
The bar plot or bar chart is usually a graph/chart that is mainly used to
represent the category of data with rectangular bars with lengths and
heights that are proportional to the values which they represent.
You can plot these bars either vertically or horizontally.
We use the bar plot to mainly show the comparison between
discrete categories of data.
In the bar plot, One axis of the plot is used to represent the
specific categories being compared, while the other axis
usually represents the measured values corresponding to
those categories.
MATPLOTLIB BAR()
FUNCTION
The bar() function is used to create a bar plot that is bounded with
a rectangle depending on the given parameters of the function. In the
Matplotlib API, this function can be used in the MATLAB style use, as
well as object-oriented API.
MATPLOTLIB BAR()
FUNCTION SYNTAX
The required syntax to use this function with axes object is as follows:
ax.bar(x, height, width, bottom, align)
The parameters of this function are described as follows:
x

This parameter is used to represent a sequence of scalar values that


represents the x coordinates of the bars. The align parameter
controls if x is the bar center (default) or left edge
height

This parameter is either a scalar or sequence of scalar


values representing the height(s) of the bars which makes the y-
axis value.
width

This parameter is either a scalar or array-like and it is optional.


The default value of this parameter is 0.8
bottom

This is also a scalar or array-like and it is optional. The default


value is None.
align

The values of this parameter are {'center', 'edge'}, optional, and the
default value of this parameter is 'center
The bar() function returns a Matplotlib container object with all bars.
Now it's time to dive into some examples of this concept.
SIMPLE BAR PLOT:
Given below is a simple example of the bar plot, which represents the
number of books offered by the institute:
import numpy as np
import matplotlib.pyplot as plt

data = {'Computer Networks':20, 'DBMS':15, 'Java':30,'C':35}


courses = list(data.keys())
values = list(data.values())
fig = plt.figure(figsize = (10, 5))
plt.bar(courses, values, color ='magenta',width = 0.4)

plt.xlabel("Books offered")
plt.ylabel("No. of books provided")
plt.title("Books provided by the institute")
plt.show()

Code Explanation:

Here plt.bar(courses, values, color='magenta') is basically specifying the bar chart that
is to be plotted using "Books offered"(by the college) column as the X-axis,
and the "No. of books" as the Y-axis.
The color attribute is basically used to set the color of the bars(magenta ).
The statement plt.xlabel("Books offered") and plt.ylabel("books provided by the institute") are
used to label the corresponding axes. The plt.title() function is used to make
a title for the graph. And the plt.show() function is used to show the graph as
the output of the previous commands.
The output shown by the above code will be as follows:
CUSTOMIZING BAR PLOT:
STACKED PLOT
The Stacked bar plots are used to represent different groups of data on the
top of one another. The height of the bar mainly depends upon the resulting
height of the combination of the results of the groups. The height goes from
the bottom to the value instead of going from zero to value
Now let us create a stacked plot and the code is given below:
import numpy as np
import matplotlib.pyplot as plt
N=5
group_a = (25, 37, 39, 23, 56)
group_b = (29, 36, 38, 25, 22)

ind = np.arange(N) # the x locations for the groups


width = 0.39
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.bar(ind, group_a, width, color='c')
ax.bar(ind, group_b, width,bottom=group_a, color='b')

ax.set_ylabel('Scores')
ax.set_title('Scores by two groups')
ax.set_xticks(ind, ('G1', 'G2', 'G3', 'G4', 'G5'))
ax.set_yticks(np.arange(0, 81, 10))
ax.legend(labels=['Group A', 'Group B'])
plt.show()
If you will run this code in your own system, then the output will be as
follows:
TIME FOR LIVE EXAMPLE!
Let us take a look at the Live example:

import numpy as np
import matplotlib.pyplot as plt
data = [[30, 25, 50, 20],[40, 23, 51, 17],[35, 22, 45, 19]]
X = np.arange(4)
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.bar(X + 0.00, data[0], color = 'c', width = 0.25)
ax.bar(X + 0.25, data[1], color = 'g', width = 0.25)
ax.bar(X + 0.50, data[2], color = 'b', width = 0.25)
plt.show()
MATPLOTLIB
HISTROGRAMS - HIST()
FUNCTION
In this tutorial, we will cover how to create histogram plots in Python using
matplotlib library.
WHAT IS HISTOGRAM?
Before diving into how to create histograms in matplotlib, let us first
understand what is a histogram?
So a histogram is an accurate representation of the distribution of
numerical data.
So Histogram is a type of bar graph and it was invented
by Karl Pearson
The Histogram is mainly used to represent the data that is
provided in some groups.
Histograms usually consist of bins of data(consecutive and
non-overlapping intervals of variables), where each bin
consists of minimum and maximum values.
To estimate the probability distribution of the continuous
variable, histogram is used.
CREATING A HISTOGRAM
There are a few steps that should be kept in mind while creating a Histogram:
1. The first step is to create the bin of the ranges.
2. The second step is to distribute the whole range of the
values into a corresponding series of intervals.
3. The third step is to count the values in each interval.
MATPLOTLIB.PYPLOT.HIST()
FUNCTION
This function is used to create the histogram.
Let us discuss the parameters of the histogram and the detailed description is
given below:
x

This parameter indicates an array or sequence of arrays.


bins

This parameter indicates an integer or sequences or any string.


density

This is an optional parameter that consists of boolean values.


range

This is an optional parameter used to indicate upper and lower


range of bins and it is also an optional parameter.
label

This is an optional parameter and is used to set the histogram axis


on a log scale.
color

This is an optional parameter used to set the color.


cumulative

If the value of this option is set to true, then a histogram is


computed where each bin gives the counts in that bin plus all bins
for smaller values.
histtype

This is an optional parameter used to specify the type of histogram


[that is bar, barstacked, step, stepfilled]. The default value of this
parameter is "bar".
align

This is an optional parameter that controls the plotting of histogram


having values [left, right, mid].
Let us take a look at a few examples to understand the concept of the
histogram.
SIMPLE HISTOGRAM
PLOT EXAMPLE:
Below we have a simple example to create a histogram:
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
x = [21,22,23,4,5,6,77,8,9,10,31,32,33,34,35,36,37,18,49,50,100]
num_bins = 5
n, bins, patches = plt.hist(x, num_bins, facecolor='orange', alpha=0.8)
plt.show()
The output in the form of histogram is as follows:
TWO HISTOGRAM IN ONE
FIGURE EXAMPLE:
Let us try two plot with two histograms together. In the code snippet given
below, we are trying to draw two histograms together:
import matplotlib.pyplot as plt
import numpy as np
plt.figure(figsize=[10,8])
x = 0.3*np.random.randn(1000)
y = 0.3*np.random.randn(1000)
n, bins, patches = plt.hist([x, y])
plt.show()
2D HISTOGRAM
EXAMPLE:
Let us try to create a two-dimensional histogram. The code snippet for the 2D
histogram is as follows:
import numpy as np
import matplotlib.pyplot as plt
mean = [0, 0]
cov = [[1, 1], [1, 2]]
x, y = np.random.multivariate_normal(mean, cov, 10000).T # x and y are array that are drawn from a
multivariate Gaussian distribution

plt.hist2d(x, y, bins=30, cmap='CMRmap') #plt.hist2d is used to draw histogram for 2D


cb = plt.colorbar()
cb.set_label('counts in bin')
plt.show()
Output Histogram is as follows:
MATPLOTLIB PIE CHART -
PIE() FUNCTION
In this tutorial, we will cover what is a Pie chart? and How to create pie
charts to represent your data using the python matplotlib library.

What is a Pie chart?

A pie chart is basically a special chart that is used to show relative sizes of
the data with the help of Pie slices. So, it is a complete circle to represent the
100% space and it creates pie slices to represent data sets.
It is a circular statistical plot that is used to display only one
series of data.
The complete area of the pie chart is equal to the total
percentage of the given data.
In the Pie Chart, the area of slices of the pie is used to
represent the percentage of the parts of the data.
The slices of the Pie are commonly known as wedges.
The area of the wedge mainly represents the percentage of that
part with respect to the whole data and can be calculated
by the length of the arc of the wedge.

Uses of Pie charts:


Few uses are given below:
1. Business Presentations(like in sales, survey results, and
operations)
2. Provides Quick Summary

Matplotlib pie() Function

The pie() function in the pyplot module of matplotlib is used to create a pie
chart representing the data in an array.
The best pie chart can be created if the figure and axes are square, or the
aspect of the Axes is equal.
The required syntax for the pie() function is given below:
matplotlib.pyplot.pie(data, explode, labels, colors, autopct, shadow)
pie() Function Parameters:

Let us discuss the parameters of this function:


1. data
This parameter is used to represents the array consisting of data values to
be plotted, the fractional area of each slice is indicated by data/sum(data). If
the sum(data)<1, then the data values return the fractional area directly,
thus resulting pie will have an empty wedge of size = 1-sum(data).
2. labels
This parameter represents a list of the sequence of strings which is used to
set the label of each wedge
3. autopct
This parameter is in the form of a string and is used to label the wedge with
their numerical value
4. colors
This parameter is used to provide color to the wedges.
5. shadow
This parameter is used to create the shadow of the wedges.
Now, its time to brush up the concept and create some pie charts. So, let's
start with some examples.
SIMPLE PIE CHART
EXAMPLE:
In the given below example we are going to create a simple pie chart in the
matplotlib:
import matplotlib.pyplot as plt
import numpy as np

subjects = ['English', 'Hindi', 'Science', 'Arts', 'Music', 'Maths']


data = [23, 17, 35, 29, 12, 41]
fig = plt.figure(figsize =(10, 7))
plt.pie(data, labels = subjects)

plt.show()
The output for the above code snippet is as shown below:
Now it's time to create some customized pie charts. Here are some aspects for
customizing the plots:
The startangle parameter is used to rotate the plot by the specified
degrees in counter-clockwise direction performed on the x-
axis of the pie chart.
The shadow parameter accepts a boolean value, if it is true then
the shadow will appear below the rim of the pie.
To customize the Wedges of the pie the wedgeprop is used which
takes Python dictionary as parameter with name values
pairs that are used to denote the wedge properties
like linewidth, edgecolor, etc.
By setting frame=True axes frame is drawn around the pie chart.
The autopct parameter mainly controls how to display the
percentage on the wedges.
CUSTOM PIE CHART
EXAMPLE:
Let us create a customized pie chart in the matplotlib:
import matplotlib.pyplot as plt

slices = [7,2,2,13]
activities = ['sleeping','cooking','working','singing']
cols = ['c','m','r','b']
plt.pie(slices,
labels=activities,
colors=cols,
startangle=90,
shadow= True,
explode=(0,0.1,0,0),
autopct='%1.1f%%')

plt.title('Customized Graph\n')
plt.show()
The output for the same is given below:
NESTED PIE CHART
EXAMPLE:
Now let us create a Nested Pie chart (also referred to as Donut Charts )and
the live example for the same is given below:

import matplotlib.pyplot as plt


import numpy as np

fig, ax = plt.subplots()

size = 0.3
vals = np.array([[60., 32.], [37., 40.], [29., 10.]])

cmap = plt.get_cmap("tab20c")
outer_colors = cmap(np.arange(3)*4)
inner_colors = cmap(np.array([1, 2, 5, 6, 9, 10]))

ax.pie(vals.sum(axis=1), radius=1, colors=outer_colors,


wedgeprops=dict(width=size, edgecolor='w'))

ax.pie(vals.flatten(), radius=1-size, colors=inner_colors,


wedgeprops=dict(width=size, edgecolor='w'))

ax.set(aspect="equal", title='Pie plot with `ax.pie`')


plt.show()
MATPLOTLIB SCATTER
PLOT - SCATTER()
FUNCTION
In this tutorial, we will cover what is a scatter plot? and how to create a
scatter plot to present your data using Matplotlib library.
The Scatter plot is a type of plot that is used to show the data as a
collection of points.
This plot is mainly used to observe the relationship between
the two variables.
Scatter plots make use of dots to represent the relationship
between two variables.
These plots are mainly used to plot data points on the
horizontal and vertical axis in order to show how much one
variable is affected by another.
In 2-Dimensions it is used to compare two variables while
in 3-Dimensions it is used to make comparisons in three
variables.
MATPLOTLIB SCATTER()
FUNCTION
The method scatter() in the pyplot module in matplotlib library of Python
is mainly used to draw a scatter plot.
The syntax to use this method is given below:
matplotlib.pyplot.scatter(x_axis_data, y_axis_data, s, c, marker, cmap, vmin, vmax,alpha,linewidths,
edgecolors)
Function Parameters:
Let us discuss the parameters of scatter() method:
x_axis_data

This parameter indicates an array containing x-axis data.


y_axis_data

This parameter indicates an array containing y-axis data.


s<

This parameter indicates the marker size (it can be scalar or array
of size equal to the size of x or y). It is an optional parameter and
the default value is None.
c

This parameter indicates the color of sequence and it is


an optional parameter with default value equals to None.
marker

This parameter is used to indicate the marker style. The default


value of this parameter is None and it is also an optional parameter.

cmap

This optional parameter indicates cmap name with default value


equals to None.
linewidths

This parameter indicates the width of the marker border and


having None as default value.
edgecolors

This parameter is used to indicate the marker border-color and


also it's default value is None.
alpha

This option indicates the blending value, between 0 (transparent)


and 1 (opaque).
Let us dive into some examples and create some scatter plots.
SIMPLE SCATTER PLOT
EXAMPLE:
Below we have a code snippet to create a simple scatter plot. Let us go
through the code snippet:
import matplotlib.pyplot as plt

x =[5, 7, 8, 7, 2, 17, 2, 9, 4, 11, 12, 9, 6]


y =[99, 86, 87, 88, 100, 86, 103, 87, 94, 78, 77, 85, 86]
plt.scatter(x, y, c ="red")
plt.show()
When you run the above code on your machine you will see the output as
shown below:
SCATTER PLOT WITH
LARGE DATASET:
Let us create another scatter plot with different random numbers and the code
snippet is given below:
import numpy as np
import matplotlib.pyplot as plt

# Creating the data


N = 1000
x = np.random.rand(N)
y = np.random.rand(N)
colors = (0,0,0)
area = np.pi*3
plt.scatter(x, y, s=area, c=colors, alpha=0.5)
plt.title('Scatter plot studytonight.com')
plt.xlabel('x')
plt.ylabel('y')
plt.show()
The output for the same is as follows:
It is important to note here that the data can be classified into several groups.
Let us understand how to create scatter plots with the group with the help of
code snippet given below:
CUSTOMIZED SCATTER
PLOT EXAMPLE:
Now we will cover the code snippet of scatter plot with the groups of heights
and weights in matplotlib:

import matplotlib.pyplot as plt


import numpy as np
weight1=[67,57.2,59.6,59.64,55.8,61.2,60.45,61]
height1=[101.7,197.6,98.3,125.1,113.7,157.7,136,148.9]
weight2=[61.9,64,62.1,64.2,62.3,65.4,62.4,61.4]
height2=[152.8,155.3,135.1,125.2,151.3,135,182.2,195.9]
weight3=[68.2,67.2,68.4,68.7,71,71.3,70.8,70]
height3=[165.8,170.9,192.8,135.4,161.4,136.1,167.1,235.1]
weight=np.concatenate((weight1,weight2,weight3))
height=np.concatenate((height1,height2,height3))
plt.scatter(weight, height, marker='^', color=['red','orange','blue'])
plt.xlabel('weight', fontsize=16)
plt.ylabel('height', fontsize=16)
plt.title('Group wise Weight vs Height scatter plot on
studytonight',fontsize=20)
plt.show()
MATPLOTLIB CONTOUR
PLOT - CONTOUR()
FUNCTION
In this tutorial, we will cover what is a contour plot and how to create
contour plots in Matplotlib.
To create a visualization of 3-Dimensional plots in 2-Dimensional space we
use contour plots in Matplotlib. Contour plots are also known as Level Plots.
Suppose there are two variables X and Y and you want to plot
them then the response of two variables will be Z and it will be
plotted as slices on the X-Y plane due to which contours are
also referred to as Z-slices or iso-response.
We should use contour plot if you want to see how the value
of Z changes as a function of two inputs that is X and Y, like
this Z = f(X,Y).
A contour line or isoline of a function of two variables is
basically a curve along which the function has a constant
value.
There are two functions in Matplotlib that is contour()(this is
used to draw the contour lines) and contourf()(this is used to
draw filled contours).

Uses of Contour Plot:

There are some uses of contour plot given below:


To visualize density.
To visualize the meteorological department.
To visualize the heights of mountains.

Matplotlib contour() Function

The function matplotlib.pyplot.contour() is useful when Z = f(X, Y) here, Z changes


as a function of input X and Y.
A contourf() function is also available in matplotlib which allows us to draw
filled contours.
This method returns a QuadContourSet. The required syntax for the same is
given below:
matplotlib.pyplot.contour([X, Y, ] Z, [levels], **kwargs)
Let us discuss the parameters of this function:
1. X, Y
This parameter indicates 2-D NumPy arrays with having same shape as Z or
same like 1-D arrays in a manner such that len(X)==M and len(Y)==N (where M
are rows and N are columns of Z)
2. Z
This parameter indicates the height values over which the contour is drawn.
The shape is (M, N).
3. levels
This parameter is used to determine the number and position of the contour
lines.
Let us cover some Examples of this function.

Simple Contour Lines Example:

In this example we will plot contour lines with the help of contour() function:
import matplotlib.pyplot as plt
import numpy as np
x_axis = np.arange(0, 80, 4)
y_axis = np.arange(0, 100, 3)
[X, Y] = np.meshgrid(x_axis, y_axis)
fig, ax = plt.subplots(1, 1)
Z = np.cos(X / 2) + np.sin(Y / 4)
ax.contour(X, Y, Z)
ax.set_title('Contour Plot')
ax.set_xlabel('x_axis')
ax.set_ylabel('y_axis')
plt.show()
Let's take another example for contour plot.

Filled Contour Plot Example:

Now let us draw a filled contour with the help of contourf() function:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-5.0, 5.0, 120)
y = np.linspace(-5.0, 5.0, 120)
X, Y = np.meshgrid(x, y)
Z = np.sqrt(X**2 + Y**2)
fig,ax=plt.subplots(1,1)
cp = ax.contourf(X, Y, Z)

ax.set_title('A filled contour plot')


ax.set_xlabel('x (cm)')
ax.set_ylabel('y (cm)')
plt.show()
MATPLOTLIB QUIVER
PLOT - QUIVER()
FUNCTION
In this tutorial, we will cover the Quiver Plot using Matplotlib Library.
To plot the 2D field of arrows, we use the Quiver plot in the matplotlib
library.
This plot mainly helps in displaying the velocity vectors as
arrows having components (u,v) at the points (x,y).
The Quiver plots are useful for Electrical engineers to
visualize electrical potential and for Mechanical engineers to
show stress gradients.
CREATING MATPLOTLIB
QUIVER PLOT
In order to create a Quiver Plot the ax.quiver() function is used.
The required syntax to use this function is as follows:
ax.quiver(x_pos, y_pos, x_dir, y_dir, color)
Following are the parameters of this function, which you can see above in
the syntax:
x_pos and y_pos

These two parameters of the function are used to indicate


the starting position of the arrows.
x_dir and y_dir

These two parameters of the function are used to indicate


the directions of the arrows.
color

This parameter is used to specify the color of the Quiver Plot.

Let us now dive into some examples related to this.


SIMPLE QUIVER PLOT
EXAMPLE:
In the example given below, we will cover how to plot a Quiver plot with
a single arrow:
import numpy as np
import matplotlib.pyplot as plt

x_pos = 0
y_pos = 0
x_direct = 1
y_direct = 1
fig, ax = plt.subplots(figsize = (10, 7))
ax.quiver(x_pos, y_pos, x_direct, y_direct)
ax.set_title('Quiver plot with a single arrow')

plt.show()
Here is the output:
TWO ARROW QUIVER
PLOT EXAMPLE:
In the example given below, we will cover how to plot a Quiver plot
with two arrows:
import numpy as np
import matplotlib.pyplot as plt

x_pos = [0, 0]
y_pos = [0, 0]
x_direct = [1, 0]
y_direct = [1, -1]
fig, ax = plt.subplots(figsize = (12, 7))
ax.quiver(x_pos, y_pos, x_direct, y_direct,scale = 8)

ax.axis([-1.5, 1.5, -1.5, 1.5])


plt.show()
Here is the output:
TIME FOR LIVE EXAMPLE!
Now we will cover a live example where we will draw the Quiver plot
using meshgrid:
import matplotlib.pyplot as plt
import numpy as np
x,y = np.meshgrid(np.arange(-3, 3, .3), np.arange(-3, 3, .35))
z = x*np.exp(-x**2 - y**2)
v, u = np.gradient(z, .2, .2)
fig, ax = plt.subplots()
q = ax.quiver(x,y,u,v)
plt.show()
In the above live example, you can even change the code and try running
other code too, to see different quiver plot outputs.
MATPLOTLIB BOX PLOT -
BOXPLOT() FUNCTION
In this tutorial, we will cover about Box plot and creation of Box plot in the
matplotlib Library using the boxplot() function.
The box plot in matplotlib is mainly used to displays a summary of a set of
data having properties like minimum, first quartile, median, third quartile,
and maximum.
The Box Plot is also known as Whisker Plot.
The box is created from the first quartile to the third quartile
in the box plot, also there is a verticle line going through the
box at the median.
In the Box Plot, the x-axis indicates the data to be
plotted while the y-axis denotes the frequency distribution.
CREATING THE BOX PLOT
The Box plot in the matplotlib library is usually created with the help
of boxplot() function.
In the Box Plot the numpy.random.normal() is used to create some
random data, it takes mean, standard deviation, and the desired
number of values as its arguments.
The provided data values to the ax.boxplot() method can be a
Numpy array or Python list or it can be Tuple of arrays

The required syntax for the boxplot() function is as follows:


matplotlib.pyplot.boxplot(data, notch, vert, patch_artist, widths)
Following are the parameters of this function:
data

This parameter indicates the array or sequence of arrays needed


to plot.
notch

This is an optional parameter that accepts boolean values. It has


None as default value.

vert

This is an optional parameter that accepts boolean values that is


false for horizontal plot and true for vertical plot respectively.
patch_artist

This is an optional parameter having boolean value with None as


its default value
widths

This is an optional parameter that accepts an array and used to set


the width of boxes. The default value is None.
Now we will dive into some examples of creating a Box plot.
CREATING A BOX PLOT
EXAMPLE:
The code for creating a simple Box plot in the Matplotlib library is as
follows:
import matplotlib.pyplot as plt

value1 = [84,77,20,40,67,62,75,78,71,32,98,89,78,67,72,82,87,66,56,52]
value2=[62,5,91,25,35,32,96,99,3,90,95,34,27,55,100,15,71,11,37,21]
value3=[23,89,12,78,72,89,25,69,68,86,19,48,15,16,16,75,65,31,25,52]
value4=[59,73,73,16,81,61,88,98,10,87,29,72,16,23,72,88,78,99,75,30]
box_plot_data=[value1,value2,value3,value4]
plt.boxplot(box_plot_data)
plt.show()
Here is the output:
CREATING A BOX PLOT
WITH FILLS AND LABELS:
In the code snippet given below, we will provide a label to the box plot and
will fill the box plot. Let us see the code for the example:
import matplotlib.pyplot as plt

value1 = [82,76,24,40,67,62,75,78,71,32,98,89,78,67,72,82,87,66,56,52]
value2=[62,5,91,25,36,32,96,95,3,90,95,32,27,55,100,15,71,11,37,21]
value3=[23,89,12,78,72,89,25,69,68,86,19,49,15,16,16,75,65,31,25,52]
value4=[59,73,70,16,81,61,88,98,10,87,29,72,16,23,72,88,78,99,75,30]
box_plot_data=[value1,value2,value3,value4]
plt.boxplot(box_plot_data,patch_artist=True,labels=['subject1','subject2','subject3','subject4'])
plt.show()
Here is the output:
CREATING A BOX PLOT
WITH NOTCH:
In this example, we will plot a box plot having a notch.
import matplotlib.pyplot as plt

value1 = [84,76,24,46,67,62,78,78,71,38,98,89,78,69,72,82,87,68,56,59]
value2=[62,5,91,25,39,32,96,99,3,98,95,32,27,55,100,15,71,11,37,29]
value3=[23,89,12,78,72,89,25,69,68,86,19,49,15,16,16,75,65,31,25,52]
value4=[59,73,70,16,81,61,88,98,10,87,29,72,16,23,72,88,78,99,75,30]
box_plot_data=[value1,value2,value3,value4]
plt.boxplot(box_plot_data,notch='True',patch_artist=True,labels=
['subject1','subject2','subject3','subject4'])
plt.show()
Here is the output:
TIME FOR LIVE EXAMPLE!
In this live example, we will draw a horizontal box plot having different
colors.

import matplotlib.pyplot as plt

value1 = [82,76,24,40,67,62,75,78,71,32,98,89,78,67,72,82,87,66,56,52]
value2=[62,5,91,25,36,32,96,95,3,90,95,32,27,55,100,15,71,11,37,21]
value3=[23,89,12,78,72,89,25,69,68,86,19,49,15,16,16,75,65,31,25,52]
value4=[59,73,70,16,81,61,88,98,10,87,29,72,16,23,72,88,78,99,75,30]

box_plot_data=[value1,value2,value3,value4]
box=plt.boxplot(box_plot_data,vert=0,patch_artist=True,labels=
['course1','course2','course3','course4'],
)

colors = ['cyan', 'maroon', 'lightgreen', 'tan']


for patch, color in zip(box['boxes'], colors):
patch.set_facecolor(color)

plt.show()
EXPLANATION OF THE
CODE
In the above example, the boxplot() function takes
argument vert=0 because we want to plot the horizontal box
plot.
The colors array in the above example will take up four
different colors and passed to four different boxes of the
boxplot with the help of patch.set_facecolor() function.
MATPLOTLIB VIOLIN
PLOT - VIOLINPLOT()
FUNCTION
In this tutorial, we will cover the Violin Plot and how to create a violin plot
using the violinplot() function in the Matplotlib library.
The Violin Plot is used to indicate the probability density of data at
different values and it is quite similar to the Matplotlib Box Plot.
These plots are mainly a combination of Box Plots and
Histograms.
The violin plot usually portrays the distribution, median,
interquartile range of data.
In this, the interquartile and median are statistical
information that is provided by the box plot whereas
the distribution is being provided by the histogram.
The violin plots are also used to represent the comparison of a
variable distribution across different "categories"; like the Box
plots.
The Violin plots are more informative as they show the full
distribution of the data.

Here is a figure showing common components of the Box Plot and Violin
Plot:
CREATION OF THE VIOLIN
PLOT
The violinplot() method is used for the creation of the violin plot.
The syntax required for the method is as follows:
violinplot(dataset, positions, vert, widths, showmeans, showextrema,showmedians,quantiles,points=1,
bw_method, *, data)
PARAMETERS
The description of the Parameters of this function is as follows:
dataset
This parameter denotes the array or sequence of vectors. It is
the input data.
positions
This parameter is used to set the positions of the violins. In this, the
ticks and limits are set automatically in order to match the positions.
It is an array-like structured data with the default as = [1, 2, …, n].
vert

This parameter contains the boolean value. If the value of this


parameter is set to true then it will create a vertical plot, otherwise,
it will create a horizontal plot.
showmeans
This parameter contains a boolean value with false as its default
value. If the value of this parameter is True, then it will toggle the
rendering of the means.
showextrema
This parameter contains the boolean values with false as its default
value. If the value of this parameter is True, then it will toggle the
rendering of the extrema.
showmedians
This parameter contains the boolean values with false as its default
value.If the value of this parameter is True, then it will toggle the
rendering of the medians.
quantiles
This is an array-like data structure having None as its default
value.If value of this parameter is not None then,it set a list of floats
in interval [0, 1] for each violin,which then stands for the quantiles
that will be rendered for that violin.
points
It is scalar in nature and is used to define the number of points to
evaluate each of the Gaussian kernel density estimations.
bw_method
This method is used to calculate the estimator bandwidth, for which
there are many different ways of calculation. The default rule used
is Scott's Rule, but you can choose ‘silverman’, a scalar constant,
or a callable.
Now its time to dive into some examples in order to clear the concepts:
VIOLIN PLOT BASIC
EXAMPLE:
Below we have a simple example where we will create violin plots for a
different collection of data.
import matplotlib.pyplot as plt
import numpy as np

np.random.seed(10)
collectn_1 = np.random.normal(120, 10, 200)
collectn_2 = np.random.normal(150, 30, 200)
collectn_3 = np.random.normal(50, 20, 200)
collectn_4 = np.random.normal(100, 25, 200)
data_to_plot = [collectn_1, collectn_2, collectn_3, collectn_4]

fig = plt.figure()
ax = fig.add_axes([0,0,1,1])

bp = ax.violinplot(data_to_plot)
plt.show()
The output will be as follows:
TIME FOR LIVE EXAMPLE!
Let us take a look at the Live example of the Violin Plot:

import numpy as np
import matplotlib.pyplot as plt
uniform = np.arange(-100, 100)
normal = np.random.normal(size = 100)*40
fig, (ax1, ax2) = plt.subplots(nrows = 1,ncols = 2, figsize =(9, 4), sharey =
True)
ax1.set_title('The Uniform Distribution')
ax1.set_ylabel('Observed values')
ax1.violinplot(uniform)
ax2.set_title('The Normal Distribution')
ax2.violinplot(normal)
plt.show()
MATPLOTLIB 3D
MATPLOTLIB 3D
PLOTTING - LINE AND
SCATTER PLOT
In this tutorial, we will cover Three Dimensional Plotting in the
Matplotlib.
It is important to note that Matplotlib was initially designed with only two-
dimensional plotting in mind. But later on, some three-dimensional
plotting utilities were built on top of Matplotlib's two-dimensional display,
which provides a set of tools for three-dimensional data visualization in
matplotlib.
Also, a 2D plot is used to show the relationships between a single pair of axes
that is x and y whereas the 3D plot, on the other hand, allows us to explore
relationships of 3 pairs of axes that is x-y, x-z, and y-z
THREE DIMENSIONAL
PLOTTING
The 3D plotting in Matplotlib can be done by enabling the utility toolkit.
The utility toolkit can be enabled by importing the mplot3d library, which
comes with your standard Matplotlib installation via pip.
After importing this sub-module, 3D plots can be created by passing the
keyword projection="3d" to any of the regular axes creation functions in
Matplotlib.
Let us cover some examples for three-dimensional plotting using this
submodule in matplotlib.
3D LINE PLOT
Here is the syntax to plot the 3D Line Plot:
Axes3D.plot(xs, ys, *args, **kwargs)
With the code snippet given below we will cover the 3D line plot in
Matplotlib:
from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = plt.axes(projection='3d')
z = np.linspace(0, 1, 100)
x = z * np.sin(30 * z)
y = z * np.cos(30 * z)

ax.plot3D(x, y, z, 'maroon')
ax.set_title('3D line plot')
plt.show()
Following is the output for it:
3D SCATTER PLOT
Here is the syntax for 3D Scatter Plot:
Axes3D.scatter(xs, ys, zs=0, zdir='z', s=20, c=None, depthshade=True, *args, **kwargs)
ARGUMENTS

Argument Description

These two arguments indicate the position of


xs, ys
data points.

It can be Either an array of the same length


as xs and ys or it can be a single value to
zs
place all points in the same plane.
The default value of this argument is 0.

This Argument is used to indicate which


zdir direction to use as z (‘x’, ‘y’ or ‘z’) at the
time of plotting a 2D set.

This argument is used to indicate the Size in


s points. It can either be a scalar or an array of
the same length as x and y.

c This argument is used to indicate the color.

This argument is used to tell Whether or not


to shade the scatter markers in order to give
depthshade the appearance of depth. The default value
of this argument is True.

With the code snippet given below we will cover the 3D Scatter plot in
Matplotlib:
fig = plt.figure()
ax = plt.axes(projection="3d")

z_line = np.linspace(0, 15, 500)


x_line = np.cos(z_line)
y_line = np.sin(z_line)
ax.plot3D(x_line, y_line, z_line, 'blue')

z_points = 15 * np.random.random(500)
x_points = np.cos(z_points) + 0.1 * np.random.randn(500)
y_points = np.sin(z_points) + 0.1 * np.random.randn(500)
ax.scatter3D(x_points, y_points, z_points, c=z_points, cmap='hsv');

plt.show()
The output is:
MATPLOTLIB 3D
CONTOUR PLOT -
CONTOUR3D() FUNCTION
In this tutorial, we will cover the Contour Plot in 3 dimensions using the
Matplotlib library.
To draw or to enable the 3d plots you just need to import the mplot3d toolkit.
There is a function named ax.contour3D() that is used to create a three-
dimensional contour plot.
This function requires all the input data to be in the form of two-
dimensional regular grids, with its Z-data evaluated at each point.
3D CONTOUR PLOT
EXAMPLE
In the example given below, we will create a 3-dimensional contour plot for
the sine function. The code snippet is as given below:
from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
import math

x = [i for i in range(0, 200, 100)]


y = [i for i in range(0, 200, 100)]
X, Y = np.meshgrid(x, y)
Z = []
for i in x:
t = []
for j in y:
t.append(math.sin(math.sqrt(i*2+j*2)))
Z.append(t)

fig = plt.figure()
ax = plt.axes(projection='3d')
ax.contour3D(X, Y, Z, 50, cmap=cm.cool)
ax.set_xlabel('a')
ax.set_ylabel('b')
ax.set_zlabel('c')
ax.set_title('3D contour Plot for sine')
plt.show()
The explanation of the functions used in the above code is as follows:
meshgrid

This is a function of NumPy library that is used to create


a rectangular grid out of two given one-dimensional arrays
representing the Cartesian or Matrix indexing.
plt.axes()

This function is used to create the object of the Axes.

ax.contour3D

This function is used to create contour


ax.set_xlabel

This function is used to set the label for the x-axis


ax.set_title()

This function is used to provide a title to the Plot


Following will be the output of the above code:
MATPLOTLIB 3D
WIREFRAME PLOT -
PLOT_WIREFRAME()
FUNCTION
In this tutorial, we will cover the 3D Wireframe plot in the matplotlib
library. We have already covered the 3D plot basics in Matplotlib library,
along with 3D Line Plot, Scatter plot and 3D contour plot.
For the data visualization using 3D wireframe, we require some modules
from matplotlib, mpl_toolkits and numpy library.
The wireframe plot basically takes a grid of values and projects it onto the
specified 3-dimensional surfaces, and it can help in making the resulting
three-dimensional forms quite easy for visualization.
To create the 3D Wireframe plot the plot_wireframe() function will be used.
Now its time to cover few examples for the 3D wireframe plot.
3D WIREFRAME PLOT
BASIC EXAMPLE:
Below we have an example where we will create a 3D Wireframe plot:
from mpl_toolkits.mplot3d import axes3d
from matplotlib import pyplot

fig = pyplot.figure()
wf = fig.add_subplot(111, projection='3d')
x, y, z = axes3d.get_test_data(0.07)
wf.plot_wireframe(x,y,z, rstride=2, cstride=2, color='maroon')
wf.set_title('3D wireframe plot')
pyplot.show()
Here is the output of the above code:
3D WIREFRAME PLOT
EXAMPLE 2:
Here is another example and code snippet for the same is given below:
from mpl_toolkits import mplot3d
import numpy

a = numpy.linspace(-5, 5, 25)
b = numpy.linspace(-5, 5, 25)
x, y = numpy.meshgrid(a, b)
z = numpy.cos(numpy.sqrt(x**2 + y**2))
fig = pyplot.figure()
wf = pyplot.axes(projection ='3d')
wf.plot_wireframe(x, y, z, color ='blue')

wf.set_title('Example 2')
pyplot.show()
Here is the output of the above code:
MATPLOTLIB 3D
SURFACE PLOT -
PLOT_SURFACE()
FUNCTION
In this tutorial, we will cover how to create a 3D Surface Plot in the
matplotlib library.
In Matplotlib's mpl_toolkits.mplot3d toolkit there is axes3d present that
provides the necessary functions that are very useful in creating 3D surface
plots.
The representation of a three-dimensional dataset is mainly termed as
the Surface Plot.
One thing is important to note that the surface plot provides a
relationship between two independent variables that are X
and Z and a designated dependent variable that is Y, rather
than just showing the individual data points.
The Surface plot is a companion plot to the Contour Plot and
it is similar to wireframe plot but there is a difference too and
it is each wireframe is basically a filled polygon.
With the help of this, the topology of the surface can be
visualized very easily.
CREATION OF 3D
SURFACE PLOT
To create the 3-dimensional surface plot the ax.plot_surface() function is used in
matplotlib.
The required syntax for this function is given below:
ax.plot_surface(X, Y, Z)
In the above syntax, the X and Y mainly indicate a 2D array of points x and y
while Z is used to indicate the 2D array of heights.
plot_surface() Attributes
Some attributes of this function are as given below:
1. shade
This attribute is used to shade the face color.
2. facecolors
This attribute is used to indicate the face color of the individual surface
3. vmax
This attribute indicates the maximum value of the map.
4. vmin
This attribute indicates the minimum value of the map.
5. norm
This attribute acts as an instance to normalize the values of color map
6. color
This attribute indicates the color of the surface
7. cmap
This attribute indicates the colormap of the surface
8. rcount
This attribute is used to indicate the number of rows to be used
The default value of this attribute is 50
9. ccount
This attribute is used to indicate the number of columns to be used
The default value of this attribute is 50
10. rstride
This attribute is used to indicate the array of row stride(that is step size)
11. cstride
This attribute is used to indicate the array of column stride(that is step size)
3D SURFACE PLOT BASIC
EXAMPLE
Below we have a code where we will use the above-mentioned function to
create a 3D Surface Plot:
from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt

x = np.outer(np.linspace(-4, 4, 33), np.ones(33))


y = x.copy().T
z = (np.sin(x **2) + np.cos(y **2) )

fig = plt.figure(figsize =(14, 9))


ax = plt.axes(projection ='3d')
ax.plot_surface(x, y, z)

plt.show()
The output for the above code is as follows:
GRADIENT SURFACE
PLOT
This plot is a combination of a 3D surface plot with a 2D contour plot. In
the Gradient surface plot, the 3D surface is colored same as the 2D contour
plot. The parts that are high on the surface contains different color rather than
the parts which are low at the surface.
The required syntax is:
ax.plot_surface(X, Y, Z, cmap, linewidth, antialiased)
where cmap is used to set the color for the surface.
GRADIENT SURFACE
PLOT EXAMPLE
Now it's time to cover a gradient surface plot. The code snippet for the same
is given below:
from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt

x = np.outer(np.linspace(-3, 3, 32), np.ones(32))


y = x.copy().T
z = (np.sin(x **2) + np.cos(y **2) )
fig = plt.figure(figsize =(14, 9))
ax = plt.axes(projection ='3d')

my_cmap = plt.get_cmap('cool')
surf = ax.plot_surface(x, y, z, cmap = my_cmap, edgecolor ='none')

fig.colorbar(surf, ax = ax, shrink = 0.7, aspect = 7)


ax.set_title('Surface plot')

plt.show()
The output for the above code is as follows:
MISCELLANEOUS
WORKING WITH TEXT IN
MATPLOTLIB
In this tutorial, we will cover working with the text in Matplotlib.
There is extensive text support in Matplotlib that includes support for
mathematical expressions, the Truetype support for raster, and vector
outputs, also there is a newline-separated text with arbitrary rotations,
and Unicode support.
WORKING WITH TEXT
The Matplotlib library has its own matplotlib.font_manager that is used to
implement a cross-platform, W3C compliant font finding algorithm.
In this, the user has great control over text properties such as
font size, font weight, text location, and color, etc.
The Matplotlib library implements a large number of TeX
math symbols and commands that provide the support for
mathematical expressions anywhere in your figure.

Given below is a list of commands that are used to create text in the Pyplot
interface as well as in Object-oriented interface:

pyplot Object-Oriented
Description
Interface Interface

This command is used to add text


text text at an arbitrary location of the
Axes.

This command is used to add an


annotation, having an optional
annotate annotate
arrow, at an arbitrary location of
theAxes.

This command is used to add a


xlabel set_xlabel
label to the Axes’s x-axis.
This command is used to add a
ylabel set_ylabel
label to the Axes’s y-axis.

This command is used to add a


title set_title
title to the Axes.

This command is used to add text


figtext text at an arbitrary location of the
Figure.

This command is used to add a


suptitle suptitle
title to the Figure.

All these functions create and return a Text instance, which can be configured
with a variety of font and other related properties.
TIME FOR EXAMPLE!!
Now its time to cover an example in which we will add different text info in
different styles to our figure:
import matplotlib.pyplot as plt
fig = plt.figure()

ax = fig.add_axes([0,0,1,1])
ax.set_title('axes title')
ax.set_xlabel('xlabel')
ax.set_ylabel('ylabel')

ax.text(3, 8, 'This is boxed italics text in data coords', style='italic',


bbox = {'facecolor': 'orange'})
ax.text(2, 6, r'an equation: $E = mc^2$', fontsize = 16)

ax.text(4, 0.05, 'This is colored text in axes coords',


verticalalignment = 'bottom', color = 'maroon', fontsize = 15)
ax.plot([2], [1], 'o')
ax.annotate('annotate', xy = (2, 1), xytext = (3, 4),
arrowprops = dict(facecolor = 'maroon', shrink = 0.05))
ax.axis([0, 10, 0, 10])
plt.show()
Following is the output for the above code:
MATHEMATICAL
EXPRESSIONS IN
MATPLOTLIB
In this tutorial, we will cover how to write mathematical expressions in
matplotlib while plotting any dataset.
WRITING
MATHEMATICAL
EXPRESSIONS
The subset TeX markup can be used in any matplotlib text string just by
placing it inside a pair of dollar signs ($).
In order to make subscripts and superscripts use
the _ and ^ symbols respectively.
To create Fractions, binomials, and stacked numbers you can
use \frac{}{}, \binom{}{} and \genfrac{}{}{}{}{}{} commands,
respectively.
Also, the Radicals can be produced with the \sqrt[]{} command.
For mathematical symbols the default font is italics.

Let us cover example for more clear understanding.


USING MATHEMATICAL
EXPRESSION:
In the example given below, we will represent subscript and superscript:
r'$\alpha_i> \beta_i$'

import numpy as np
import matplotlib.pyplot as plt
t = np.arange(0.0, 2.0, 0.01)
s = np.cos(1*np.pi*t)
plt.plot(t,s)
plt.title(r'$\alpha_i> \beta_i$', fontsize=20)

plt.text(0.6, 0.6, r'$\mathcal{A}\mathrm{cos}(2 \omega t)$', fontsize = 20)


plt.xlabel('The time (s)')
plt.ylabel('volts (mV)')
plt.show()
Following is the output of the above code:
WORKING WITH IMAGES
IN MATPLOTLIB
In this tutorial, we will cover how to work with images in the Matplotlib
library.
In Matploltlib library, The image module is used for adding images in plots
and figures.
Only PNG images are supported by matplotlib.
There are two useful and important methods of the image
module imread(it is used to read images) and imshow (it is used to
display the image).

Now we will cover some examples showing how you can work with
images:
EXAMPLE 1:
In the code snippet, we will read the image using imread() and then display the
image using imshow():
import matplotlib.pyplot as plt
import matplotlib.image as img

testImage = img.imread('C:\\Users\\StudyTonight\\Desktop\\logoo.png')

plt.imshow(testImage)
Following will be the output:
EXAMPLE 2:
In the code example given below, we read the image using imread() and then
represent it in the form of an array:
import matplotlib.pyplot as plt
import matplotlib.image as img

testImage = img.imread('C:\\Users\\StudyTonight\\Desktop\\logoo.png')

print(testImage)
[[[1. 1. 1. 1.] [1. 1. 1. 1.] [1. 1. 1. 1.] ... [1. 1. 1. 1.] [1. 1. 1. 1.] [1. 1. 1. 1.]]
[[1. 1. 1. 1.] [1. 1. 1. 1.] [1. 1. 1. 1.] ... [1. 1. 1. 1.] [1. 1. 1. 1.] [1. 1. 1. 1.]] [[1.
1. 1. 1.] [1. 1. 1. 1.] [1. 1. 1. 1.] ... [1. 1. 1. 1.] [1. 1. 1. 1.] [1. 1. 1. 1.]] ... [[1.
1. 1. 1.] [1. 1. 1. 1.] [1. 1. 1. 1.] ... [1. 1. 1. 1.] [1. 1. 1. 1.] [1. 1. 1. 1.]] [[1. 1.
1. 1.] [1. 1. 1. 1.] [1. 1. 1. 1.] ... [1. 1. 1. 1.] [1. 1. 1. 1.] [1. 1. 1. 1.]] [[1. 1. 1.
1.] [1. 1. 1. 1.] [1. 1. 1. 1.] ... [1. 1. 1. 1.] [1. 1. 1. 1.] [1. 1. 1. 1.]]]
EXAMPLE 3:
In the example given below, we will modify all the parameters of the image:
import matplotlib.pyplot as plt
import matplotlib.image as img
testImage = img.imread('C:\\Users\\StudyTonight\\Desktop\\logoo.png')

print(testImage.shape)
modifiedImage = testImage[50:200, 100:200, 1]

plt.imshow(modifiedImage)
In the above code, the height of the image is 150 pixels (that is displayed
from the 50th pixel), width is 100 pixels (that is displayed from the 100th
pixel) and the mode value is 1.
Following is the output of the above code:
CONCLUSION:
With this we come to an end for our Matplotlib tutorial. We will keep on
adding more tutorial pages and guides to this tutorial along with some
applications for Matplotlib plots and figures.

You might also like