Matplotlib-Tutorial
Matplotlib-Tutorial
net
Matplotlib Tutorial
Matplotlib Tutorial .............................................................................................................. 1
1. Matplotlib Tutorial ......................................................................................................... 3
2. Matplotlib - Environment Setup .................................................................................... 3
3. Matplotlib - Anaconda distribution................................................................................ 4
4. Matplotlib - Jupyter Notebook ....................................................................................... 5
5. Matplotlib - Pyplot API ................................................................................................. 8
6. Matplotlib - Simple Plot .............................................................................................. 13
7. Matplotlib - PyLab module .......................................................................................... 16
7. Matplotlib - Object-oriented Interface ......................................................................... 18
8. Matplotlib - Figure Class ............................................................................................. 21
9. Matplotlib - Axes Class ............................................................................................... 22
10. Matplotlib – Multiplots .............................................................................................. 25
11. Matplotlib - Subplots() Function ............................................................................... 28
12. Matplotlib - Subplot2grid() Function ........................................................................ 29
13. Matplotlib – Grids ...................................................................................................... 30
14. Matplotlib - Formatting Axes .................................................................................... 31
15. Matplotlib - Setting Limits ........................................................................................ 33
16. Matplotlib - Setting Ticks and Tick Labels ............................................................... 35
17. Matplotlib - Twin Axes.............................................................................................. 36
18. Matplotlib - Bar Plot .................................................................................................. 37
19. Matplotlib – Histogram .............................................................................................. 41
20. Matplotlib - Pie Chart ................................................................................................ 43
21. Matplotlib - Scatter Plot ............................................................................................. 45
22. Matplotlib - Contour Plot ........................................................................................... 46
23. Matplotlib - Quiver Plot ............................................................................................. 47
24. Matplotlib - Box Plot ................................................................................................. 48
25. Matplotlib - Violin Plot.............................................................................................. 50
26. Matplotlib - Three-dimensional Plotting ................................................................... 51
27. Matplotlib - 3D Contour Plot ..................................................................................... 53
28. Matplotlib - 3D Wireframe plot ................................................................................. 54
29. Matplotlib - 3D Surface plot ...................................................................................... 55
30. Matplotlib - Working With Text ................................................................................ 56
31. Matplotlib - Mathematical Expressions ..................................................................... 58
Python Tutorials 1
[Link]
Python Tutorials 2
[Link]
1. Matplotlib Tutorial
Matplotlib is one of the most popular Python packages used for data visualization.
It is a cross-platform library for making 2D plots from data in arrays. It provides an
object-oriented API that helps in embedding plots in applications using Python GUI
toolkits such as PyQt, WxPythonotTkinter. It can be used in Python and IPython
shells, Jupyter notebook and web application servers also.
Audience
This tutorial is designed for those learners who wish to acquire knowledge on the
basics of data visualization.
Prerequisites
Matplotlib is written in Python and makes use of NumPy, the numerical
mathematics extension of Python. We assume that the readers of this tutorial have
basic knowledge of Python.
Matplotlib is one of the most popular Python packages used for data visualization.
It is a cross-platform library for making 2D plots from data in arrays. Matplotlib is
written in Python and makes use of NumPy, the numerical mathematics extension
of Python. It provides an object-oriented API that helps in embedding plots in
applications using Python GUI toolkits such as PyQt, WxPythonotTkinter. It can be
used in Python and IPython shells, Jupyter notebook and web application servers
also.
Matplotlib has a procedural interface named the Pylab, which is designed to
resemble MATLAB, a proprietary programming language developed by
MathWorks. Matplotlib along with NumPy can be considered as the open source
equivalent of MATLAB.
Matplotlib was originally written by John D. Hunter in 2003. The current stable
version is 2.2.0 released in January 2018.
Python Tutorials 3
[Link]
• tk
• PyQt4
• PyQt5
• pygtk
• wxpython
• pycairo
• Tornado
For better support of animation output format and image file formats, LaTeX, etc.,
you can install the following −
• _mpeg/avconv
• ImageMagick
• Pillow (>=2.0)
• LaTeX and GhostScript (for rendering text with LaTeX).
• LaTeX and GhostScript (for rendering text with LaTeX).
Python Tutorials 4
[Link]
Python Tutorials 5
[Link]
In 2014, Fernando Pérez announced a spin-off project from IPython called Project
Jupyter. IPython will continue to exist as a Python shell and a kernel for Jupyter,
while the notebook and other language-agnostic parts of IPython will move under
the Jupyter name. Jupyter added support for Julia, R, Haskell and Ruby.
To start the Jupyter notebook, open Anaconda navigator (a desktop graphical user
interface included in Anaconda that allows you to launch applications and easily
manage Conda packages, environments and channels without the need to use
command line commands).
Python Tutorials 6
[Link]
You will see the application opening in the web browser on the following address
− [Link]
You probably want to start by making a new notebook. You can easily do this by
clicking on the "New button" in the "Files tab". You see that you have the option to
make a regular text file, a folder, and a terminal. Lastly, you will also see the option
to make a Python 3 notebook.
Python Tutorials 7
[Link]
Python Tutorials 8
[Link]
1 Bar
Make a bar plot.
2 Barh
Make a horizontal bar plot.
3 Boxplot
Python Tutorials 9
[Link]
4 Hist
Plot a histogram.
5 hist2d
Make a 2D histogram plot.
6 Pie
Plot a pie chart.
7 Plot
Plot lines and/or markers to the Axes.
8 Polar
Make a polar plot..
9 Scatter
Make a scatter plot of x vs y.
10 Stackplot
Draws a stacked area plot.
11 Stem
Create a stem plot.
12 Step
Make a step plot.
13 Quiver
Plot a 2-D field of arrows.
Python Tutorials 10
[Link]
Image Functions
[Link] Function & Description
1 Imread
Read an image from a file into an array.
2 Imsave
Save an array as in image file.
3 Imshow
Display an image on the axes.
Axis Functions
[Link] Function & Description
1
Axes
Add axes to the figure.
2 Text
Add text to the axes.
3 Title
Set a title of the current axes.
4 Xlabel
Set the x axis label of the current axis.
5 Xlim
Get or set the x limits of the current axes.
6 Xscale
Python Tutorials 11
[Link]
7 Xticks
Get or set the x-limits of the current tick locations and labels.
8 Ylabel
Set the y axis label of the current axis.
9 Ylim
Get or set the y-limits of the current axes.
10 Yscale
Set the scaling of the y-axis.
11 Yticks
Get or set the y-limits of the current tick locations and labels.
Figure Functions
[Link] Function & Description
1 Figtext
Add text to figure.
2 Figure
Creates a new figure.
3 Show
Display a figure.
4 Savefig
Save the current figure.
Python Tutorials 12
[Link]
5 Close
Close a figure window.
Next we need an array of numbers to plot. Various array functions are defined in
the NumPy library which is imported with the np alias.
import numpy as np
We now obtain the ndarray object of angles between 0 and 2π using the arange()
function from the NumPy library.
x = [Link](0, [Link]*2, 0.05)
The ndarray object serves as values on x axis of the graph. The corresponding sine
values of angles in x to be displayed on y axis are obtained by the following
statement −
y = [Link](x)
The values from two arrays are plotted using the plot() function.
[Link](x,y)
You can set the plot title, and labels for x and y axes.
You can set the plot title, and labels for x and y axes.
[Link]("angle")
[Link]("sine")
[Link]('sine wave')
Python Tutorials 13
[Link]
y = [Link](x)
[Link](x,y)
[Link]("angle")
[Link]("sine")
[Link]('sine wave')
[Link]()
When the above line of code is executed, the following graph is displayed −
To display plot outputs inside the notebook itself (and not in the separate viewer),
enter the following magic statement −
%matplotlib inline
Python Tutorials 14
[Link]
Obtain x as the ndarray object containing angles in radians between 0 to 2π, and
y as sine value of each angle −
import math
x = [Link](0, [Link]*2, 0.05)
y = [Link](x)
Finally execute the plot() function to generate the sine wave display in the notebook
(no need to run the show() function) −
[Link](x,y)
After the execution of the final line of code, the following output is displayed −
Python Tutorials 15
[Link]
Python Tutorials 16
[Link]
colors b, g, r, c, m, y, k, w
Plots can be overlaid. Just use the multiple plot commands. Use clf() to clear the
plot.
from pylab import *
plot(x, sin(x))
plot(x, cos(x), 'r-')
plot(x, -sin(x), 'g--')
show()
Python Tutorials 17
[Link]
Now add axes to figure. The add_axes() method requires a list object of 4
elements corresponding to left, bottom, width and height of the figure. Each number
must be between 0 and 1 −
ax=fig.add_axes([0,0,1,1])
Python Tutorials 18
[Link]
If you are using Jupyter notebook, the %matplotlib inline directive has to be issued;
the otherwistshow() function of pyplot module displays the plot.
Consider executing the following code −
from matplotlib import pyplot as plt
import numpy as np
import math
x = [Link](0, [Link]*2, 0.05)
y = [Link](x)
fig = [Link]()
ax = fig.add_axes([0,0,1,1])
[Link](x,y)
ax.set_title("sine wave")
ax.set_xlabel('angle')
ax.set_ylabel('sine')
[Link]()
Output
The above line of code generates the following output −
Python Tutorials 19
[Link]
The same code when run in Jupyter notebook shows the output as shown below −
Python Tutorials 20
[Link]
Python Tutorials 21
[Link]
The following member functions of axes class add different elements to plot −
Legend
The legend() method of axes class adds a legend to the plot figure. It takes three
parameters −
[Link](handles, labels, loc)
Best 0
upper right 1
upper left 2
Python Tutorials 22
[Link]
lower left 3
lower right 4
Right 5
Center left 6
Center right 7
lower center 8
upper center 9
Center 10
[Link]()
This is the basic method of axes class that plots values of one array versus another
as lines or markers. The plot() method can have an optional format string argument
to specify color, style and size of line and marker.
Color codes
Character Color
‘b’ Blue
‘g’ Green
‘r’ Red
‘b’ Blue
‘c’ Cyan
‘m’ Magenta
‘y’ Yellow
‘k’ Black
‘b’ Blue
‘w’ White
Marker codes
Character Description
Python Tutorials 23
[Link]
‘x’ X marker
Following example shows the advertisement expenses and sales figures of TV and
smartphone in the form of line plots. Line representing TV is a solid line with yellow
colour and square markers whereas smartphone line is a dashed line with green
colour and circle marker.
import [Link] as plt
y = [1, 4, 9, 16, 25,36,49, 64]
x1 = [1, 16, 30, 42,55, 68, 77,88]
x2 = [1,6,12,18,28, 40, 52, 65]
fig = [Link]()
ax = fig.add_axes([0,0,1,1])
l1 = [Link](x1,y,'ys-') # solid line with yellow colour and
square marker
l2 = [Link](x2,y,'go--') # dash line with green colour and
circle marker
[Link](labels = ('tv', 'Smartphone'), loc = 'lower right') #
legend placed at lower right
ax.set_title("Advertisement effect on sales")
ax.set_xlabel('medium')
ax.set_ylabel('sales')
[Link]()
When the above line of code is executed, it produces the following plot −
Python Tutorials 24
[Link]
In the current figure, the function creates and returns an Axes object, at position
index of a grid of nrows by ncolsaxes. Indexes go from 1 to nrows * ncols,
incrementing in row-major [Link], ncols and index are all less than 10. The
indexes can also be given as single, concatenated, threedigitnumber.
For example, subplot(2, 3, 3) and subplot(233) both create an Axes at the top right
corner of the current figure, occupying half of the figure height and a third of the
figure width.
Creating a subplot will delete any pre-existing subplot that overlaps with it beyond
sharing a boundary.
import [Link] as plt
# plot a line, implicitly creating a subplot(111)
[Link]([1,2,3])
# now create a subplot which represents the top plot of a grid
with 2 rows and 1 column.
Python Tutorials 25
[Link]
#Since this subplot will overlap the first, the plot (and its
axes) previously
created, will be removed
[Link](211)
[Link](range(12))
[Link](212, facecolor='y') # creates 2nd subplot with
yellow background
[Link](range(12))
The add_subplot() function of the figure class will not overwrite the existing plot −
import [Link] as plt
fig = [Link]()
ax1 = fig.add_subplot(111)
[Link]([1,2,3])
ax2 = fig.add_subplot(221, facecolor='y')
[Link]([1,2,3])
When the above line of code is executed, it generates the following output −
Python Tutorials 26
[Link]
You can add an insert plot in the same figure by adding another axes object in the
same figure canvas.
import [Link] as plt
import numpy as np
import math
x = [Link](0, [Link]*2, 0.05)
fig=[Link]()
axes1 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # main axes
axes2 = fig.add_axes([0.55, 0.55, 0.3, 0.3]) # inset axes
y = [Link](x)
[Link](x, y, 'b')
[Link](x,[Link](x),'r')
axes1.set_title('sine')
axes2.set_title("cosine")
[Link]()
Upon execution of the above line of code, the following output is generated −
Python Tutorials 27
[Link]
Python Tutorials 28
[Link]
a[1][0].plot(x,[Link](x))
a[1][0].set_title('exp')
a[1][1].plot(x,np.log10(x))
a[1][1].set_title('log')
[Link]()
In the following example, a 3X3 grid of the figure object is filled with axes objects
of varying sizes in row and column spans, each showing a different plot.
import [Link] as plt
a1 = plt.subplot2grid((3,3),(0,0),colspan = 2)
a2 = plt.subplot2grid((3,3),(0,2), rowspan = 3)
a3 = plt.subplot2grid((3,3),(1,0),rowspan = 2, colspan = 2)
import numpy as np
x = [Link](1,10)
Python Tutorials 29
[Link]
[Link](x, x*x)
a2.set_title('square')
[Link](x, [Link](x))
a1.set_title('exp')
[Link](x, [Link](x))
a3.set_title('log')
plt.tight_layout()
[Link]()
Upon execution of the above line code, the following output is generated −
Python Tutorials 30
[Link]
axes[2].set_title('no grid')
fig.tight_layout()
[Link]()
Python Tutorials 31
[Link]
Axis spines are the lines connecting axis tick marks demarcating boundaries of plot
area. The axes object has spines located at top, bottom, left and right.
Each spine can be formatted by specifying color and width. Any edge can be made
invisible if its color is set to none.
import [Link] as plt
fig = [Link]()
ax = fig.add_axes([0,0,1,1])
[Link]['bottom'].set_color('blue')
[Link]['left'].set_color('red')
[Link]['left'].set_linewidth(2)
[Link]['right'].set_color(None)
[Link]['top'].set_color(None)
[Link]([1,2,3,4,5])
[Link]()
Python Tutorials 32
[Link]
Python Tutorials 33
[Link]
Python Tutorials 34
[Link]
This method will mark the data points at the given positions with ticks.
Similarly, labels corresponding to tick marks can be set
by set_xlabels() and set_ylabels() functions respectively.
ax.set_xlabels([‘two’, ‘four’,’six’, ‘eight’, ‘ten’])
This will display the text labels below the markers on the x axis.
Following example demonstrates the use of ticks and labels.
import [Link] as plt
import numpy as np
Python Tutorials 35
[Link]
import math
x = [Link](0, [Link]*2, 0.05)
fig = [Link]()
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # main axes
y = [Link](x)
[Link](x, y)
ax.set_xlabel(‘angle’)
ax.set_title('sine')
ax.set_xticks([0,2,4,6])
ax.set_xticklabels(['zero','two','four','six'])
ax.set_yticks([-1,0,1])
[Link]()
Python Tutorials 36
[Link]
a1.set_ylabel('exp')
a2 = [Link]()
[Link](x, [Link](x),'ro-')
a2.set_ylabel('log')
[Link](labels = ('exp','log'),loc='upper left')
[Link]()
The function makes a bar plot with the bound rectangle of size (x −width = 2; x +
width=2; bottom; bottom + height).
The parameters to the function are −
Python Tutorials 37
[Link]
width scalar or array-like, optional. the width(s) of the bars default 0.8
bottom scalar or array-like, optional. the y coordinate(s) of the bars default None.
Python Tutorials 38
[Link]
When comparing several quantities and when changing one variable, we might
want a bar chart where we have bars of one color for one quantity value.
We can plot multiple bar charts by playing with the thickness and the positions of
the bars. The data variable contains three series of four values. The following script
will show three bar charts of four bars. The bars will have a thickness of 0.25 units.
Each bar chart will be shifted 0.25 units from the previous one. The data object is
a multidict containing number of students passed in three branches of an
engineering college over the last four years.
import numpy as np
import [Link] as plt
data = [[30, 25, 50, 20],
[40, 23, 51, 17],
[35, 22, 45, 19]]
X = [Link](4)
fig = [Link]()
ax = fig.add_axes([0,0,1,1])
[Link](X + 0.00, data[0], color = 'b', width = 0.25)
[Link](X + 0.25, data[1], color = 'g', width = 0.25)
[Link](X + 0.50, data[2], color = 'r', width = 0.25)
Python Tutorials 39
[Link]
The stacked bar chart stacks bars that represent different groups on top of each
other. The height of the resulting bar shows the combined result of the groups.
The optional bottom parameter of the [Link]() function allows you to specify a
starting value for a bar. Instead of running from zero to a value, it will go from the
bottom to the value. The first call to [Link]() plots the blue bars. The second
call to [Link]() plots the red bars, with the bottom of the blue bars being at the
top of the red bars.
import numpy as np
import [Link] as plt
N = 5
menMeans = (20, 35, 30, 35, 27)
womenMeans = (25, 32, 34, 20, 25)
ind = [Link](N) # the x locations for the groups
width = 0.35
fig = [Link]()
ax = fig.add_axes([0,0,1,1])
[Link](ind, menMeans, width, color='r')
[Link](ind, womenMeans, width,bottom=menMeans, color='b')
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(ind, ('G1', 'G2', 'G3', 'G4', 'G5'))
ax.set_yticks([Link](0, 81, 10))
[Link](labels=['Men', 'Women'])
[Link]()
Python Tutorials 40
[Link]
Python Tutorials 41
[Link]
optional parameters
density If True, the first element of the return tuple will be the counts normalized to
form a probability density
cumulative If True, then a histogram is computed where each bin gives the counts in that
bin plus all bins for smaller values.
Python Tutorials 42
[Link]
labels list. A sequence of strings providing the labels for each wedge.
Python Tutorials 43
[Link]
Colors A sequence of matplotlibcolorargs through which the pie chart will cycle. If None,
will use the colors in the currently active cycle.
Autopct string, used to label the wedges with their numeric value. The label will be placed
inside the wedge. The format string will be fmt%pct.
Following code uses the pie() function to display the pie chart of the list of students
enrolled for various computer language courses. The proportionate percentage is
displayed inside the respective wedge with the help of autopct parameter which is
set to %1.2f%.
from matplotlib import pyplot as plt
import numpy as np
fig = [Link]()
ax = fig.add_axes([0,0,1,1])
[Link]('equal')
langs = ['C', 'C++', 'Java', 'Python', 'PHP']
students = [23,17,35,29,12]
[Link](students, labels = langs,autopct='%1.2f%%')
[Link]()
Python Tutorials 44
[Link]
Python Tutorials 45
[Link]
Python Tutorials 46
[Link]
The above command plots vectors as arrows at the coordinates specified in each
corresponding pair of elements in x and y.
Parameters
The following table lists down the different parameters for the Quiver plot −
Python Tutorials 47
[Link]
Python Tutorials 48
[Link]
line goes through the box at the median. The whiskers go from each quartile to the
minimum or maximum.
The list of arrays that we created above is the only required input for creating the
boxplot. Using the data_to_plot line of code, we can create the boxplot with the
following code −
fig = [Link]()
# Create an axes instance
ax = fig.add_axes([0,0,1,1])
# Create the boxplot
bp = [Link](data_to_plot)
[Link]()
Python Tutorials 49
[Link]
[Link](10)
collectn_1 = [Link](100, 10, 200)
collectn_2 = [Link](80, 30, 200)
collectn_3 = [Link](90, 20, 200)
collectn_4 = [Link](70, 25, 200)
Python Tutorials 50
[Link]
fig = [Link]()
Python Tutorials 51
[Link]
x = z * [Link](20 * z)
y = z * [Link](20 * z)
ax.plot3D(x, y, z, 'gray')
ax.set_title('3D line plot')
[Link]()
We can now plot a variety of three-dimensional plot types. The most basic three-
dimensional plot is a 3D line plot created from sets of (x, y, z) triples. This can be
created using the ax.plot3D function.
Python Tutorials 52
[Link]
x = [Link](-6, 6, 30)
y = [Link](-6, 6, 30)
X, Y = [Link](x, y)
Z = f(X, Y)
fig = [Link]()
ax = [Link](projection='3d')
ax.contour3D(X, Y, Z, 50, cmap='binary')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
Python Tutorials 53
[Link]
ax.set_title('3D contour')
[Link]()
x = [Link](-6, 6, 30)
y = [Link](-6, 6, 30)
X, Y = [Link](x, y)
Z = f(X, Y)
fig = [Link]()
ax = [Link](projection='3d')
ax.plot_wireframe(X, Y, Z, color='black')
ax.set_title('wireframe')
[Link]()
Python Tutorials 54
[Link]
fig = [Link]()
ax = [Link](projection='3d')
Python Tutorials 55
[Link]
Python Tutorials 56
[Link]
ax = fig.add_axes([0,0,1,1])
ax.set_title('axes title')
ax.set_xlabel('xlabel')
ax.set_ylabel('ylabel')
[Link](3, 8, 'boxed italics text in data coords',
style='italic',
bbox = {'facecolor': 'red'})
[Link](2, 6, r'an equation: $E = mc^2$', fontsize = 15)
[Link](4, 0.05, 'colored text in axes coords',
verticalalignment = 'bottom', color = 'green', fontsize = 15)
[Link]([2], [1], 'o')
[Link]('annotate', xy = (2, 1), xytext = (3, 4),
arrowprops = dict(facecolor = 'black', shrink = 0.05))
[Link]([0, 10, 0, 10])
[Link]()
Python Tutorials 57
[Link]
To make subscripts and superscripts, use the '_' and '^' symbols −
r'$\alpha_i> \beta_i$'
import numpy as np
import [Link] as plt
t = [Link](0.0, 2.0, 0.01)
s = [Link](2*[Link]*t)
[Link](t,s)
[Link](r'$\alpha_i> \beta_i$', fontsize=20)
Python Tutorials 58
[Link]
[Link]()
Python Tutorials 59
[Link]
Any array containing image data can be saved to a disk file by executing
the imsave() function. Here a vertically flipped version of the original png file is
saved by giving origin parameter as lower.
[Link]("[Link]", img, cmap = 'gray', origin = 'lower')
Data [Link] The user land data coordinate system. controlled by the
xlim and ylim
Axes [Link] The coordinate system of the Axes. (0,0) is bottom left
and (1,1) is top right of the axes.
Python Tutorials 60
[Link]
Figure [Link] The coordinate system of the Figure. (0,0) is bottom left
and (1,1) is top right of the figure
Python Tutorials 61