Matplotlib Tutorial Learn Matplotlib by Examples B08XYJB9K3
Matplotlib Tutorial Learn Matplotlib by Examples B08XYJB9K3
LEARN MATPLOTLIB BY
EXAMPLES.
Instructions are clear, concise and effective
Theory, Principles and Practice
-------------------------------------------------
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.
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:
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')
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
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.
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.
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
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.
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.
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.
super().__init__(*args, **kwargs)
self.text(0.9, 0.98, figtitle, ha='center')
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:
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.
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
fig = plt.figure()
#[left, bottom, width, height]
ax = plt.axes([0.2, 0.2, 0.8, 0.8])
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.
Character Color
‘b’ Blue
‘g’ Green
‘r’ Red
‘b’ Blue
‘c’ Cyan
‘m’ Magenta
‘y’ Yellow
‘k’ Black
‘b’ Blue
‘w’ White
Character Description
‘x’ X marker
Diamond
‘D’
marker
Hexagon
‘H’
marker
Character Description
Hexagon
‘H’
marker
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
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.
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)
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.
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
fig, ax = plt.subplots(2, 2)
x = np.linspace(0, 8, 1000)
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
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
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
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.
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.
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]
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
For y-axis:
Axes.set_ylim(self, bottom=None, top=None, emit=True, auto=False, \*, ymin=None, ymax=None)
Function Parameters:
bottom and top
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]
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)
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.
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.
# 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
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
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
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
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)
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
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.
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:
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:
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]))
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
cmap
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.
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)
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)
vert
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.
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'],
)
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
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
With the code snippet given below we will cover the 3D Scatter plot in
Matplotlib:
fig = plt.figure()
ax = plt.axes(projection="3d")
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
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
ax.contour3D
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
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
my_cmap = plt.get_cmap('cool')
surf = ax.plot_surface(x, y, z, cmap = my_cmap, edgecolor ='none')
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
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')
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)
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.