Matplotlib EBOOK
Matplotlib EBOOK
#matplotlib
Table of Contents
About 1
Remarks 2
Overview 2
Versions 2
Examples 2
Windows 2
OS X 2
Linux 3
Debian/Ubuntu 3
Fedora/Red Hat 3
Troubleshooting 3
Introduction 8
Examples 8
Examples 14
Scatter Plots 14
Shaded Plots 16
Shaded region below a line 16
Line plots 18
Data plot 20
Heatmap 22
Chapter 4: Boxplots 26
Examples 26
Basic Boxplots 26
Chapter 5: Boxplots 28
Examples 28
Boxplot function 28
Syntax 35
Examples 35
Chapter 7: Colormaps 36
Examples 36
Basic usage 36
Examples 44
Remarks 46
Examples 47
Coordinate systems and text 47
Examples 50
Creating a figure 50
Creating an axes 50
Examples 52
Examples 55
Simple histogram 55
Examples 56
Opening images 56
Remarks 58
Examples 58
Examples 62
Simple Legend 62
Introduction 71
Examples 71
LogLog graphing 71
Chapter 17: Multiple Plots 74
Syntax 74
Examples 74
Remarks 87
Examples 90
Credits 92
About
You can share this PDF with anyone you feel could benefit from it, downloaded the latest version
from: matplotlib
It is an unofficial and free matplotlib ebook created for educational purposes. All the content is
extracted from Stack Overflow Documentation, which is written by many hardworking individuals at
Stack Overflow. It is neither affiliated with Stack Overflow nor official matplotlib.
The content is released under Creative Commons BY-SA, and the list of contributors to each
chapter are provided in the credits section at the end of this book. Images may be copyright of
their respective owners unless otherwise specified. All trademarks and registered trademarks are
the property of their respective company owners.
Use the content presented in this book at your own risk; it is not guaranteed to be correct nor
accurate, please send your feedback and corrections to info@zzzprojects.com
https://riptutorial.com/ 1
Chapter 1: Getting started with matplotlib
Remarks
Overview
matplotlib is a plotting library for Python. It provides object-oriented APIs for embedding plots into
applications. It is similar to MATLAB in capacity and syntax.
It was originally written by J.D.Hunter and is actively being developed. It is distributed under a
BSD-Style License.
Versions
Examples
Installation and Setup
There are several ways to go about installing matplotlib, some of which will depend on the system
you are using. If you are lucky, you will be able to use a package manager to easily install the
matplotlib module and its dependencies.
Windows
On Windows machines you can try to use the pip package manager to install matplotlib. See here
for information on setting up pip in a Windows environment.
OS X
It is recommended that you use the pip package manager to install matplotlib. If you need to install
some of the non-Python libraries on your system (e.g. libfreetype) then consider using homebrew.
https://riptutorial.com/ 2
If you cannot use pip for whatever reason, then try to install from source.
Linux
Ideally, the system package manager or pip should be used to install matplotlib, either by installing
the python-matplotlib package or by running pip install matplotlib.
If this is not possible (e.g. you do not have sudo privileges on the machine you are using), then
you can install from source using the --user option: python setup.py install --user. Typically, this
will install matplotlib into ~/.local.
Debian/Ubuntu
sudo apt-get install python-matplotlib
Fedora/Red Hat
sudo yum install python-matplotlib
Troubleshooting
See the matplotlib website for advice on how to fix a broken matplotlib.
plt.style.use('ggplot')
fig = plt.figure(1)
ax = plt.gca()
plt.draw()
https://riptutorial.com/ 3
# Customize the plot
ax.grid(1, ls='--', color='#777777', alpha=0.5, lw=1)
ax.tick_params(labelsize=12, length=0)
ax.set_axis_bgcolor('w')
# add a legend
leg = plt.legend( ['text'], loc=1 )
fr = leg.get_frame()
fr.set_facecolor('w')
fr.set_alpha(.7)
plt.draw()
https://riptutorial.com/ 4
Imperative vs. Object-oriented Syntax
Matplotlib supports both object-oriented and imperative syntax for plotting. The imperative syntax
is intentionally designed to be very close to Matlab syntax.
The imperative syntax (sometimes called 'state-machine' syntax) issues a string of commands all
of which act on the most recent figure or axis (like Matlab). The object-oriented syntax, on the
other hand, explicitly acts on the objects (figure, axis, etc.) of interest. A key point in the zen of
Python states that explicit is better than implicit so the object-oriented syntax is more pythonic.
However, the imperative syntax is convenient for new converts from Matlab and for writing small,
"throwaway" plot scripts. Below is an example of the two different styles.
t = np.arange(0, 2, 0.01)
y = np.sin(4 * np.pi * t)
# Imperative syntax
plt.figure(1)
https://riptutorial.com/ 5
plt.clf()
plt.plot(t, y)
plt.xlabel('Time (s)')
plt.ylabel('Amplitude (V)')
plt.title('Sine Wave')
plt.grid(True)
https://riptutorial.com/ 6
Display a two dimensional (2D) array on the axes.
import numpy as np
from matplotlib.pyplot import imshow, show, colorbar
image = np.random.rand(4,4)
imshow(image)
colorbar()
show()
https://riptutorial.com/ 7
Chapter 2: Animations and interactive
plotting
Introduction
With python matplotlib you can properly make animated graphs.
Examples
Basic animation with FuncAnimation
The matplotlib.animation package offer some classes for creating animations. FuncAnimation
creates animations by repeatedly calling a function. Here we use a function animate() that changes
the coordinates of a point on the graph of a sine function.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
TWOPI = 2*np.pi
fig, ax = plt.subplots()
ax = plt.axis([0,TWOPI,-1,1])
def animate(i):
redDot.set_data(i, np.sin(i))
return redDot,
plt.show()
https://riptutorial.com/ 8
Save animation to gif
In this example we use the save method to save an Animation object using ImageMagick.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import rcParams
# make sure the full paths for ImageMagick and ffmpeg are configured
rcParams['animation.convert_path'] = r'C:\Program Files\ImageMagick\convert'
rcParams['animation.ffmpeg_path'] = r'C:\Program Files\ffmpeg\bin\ffmpeg.exe'
TWOPI = 2*np.pi
fig, ax = plt.subplots()
https://riptutorial.com/ 9
ax = plt.axis([0,TWOPI,-1,1])
def animate(i):
redDot.set_data(i, np.sin(i))
return redDot,
For interacting with plots Matplotlib offers GUI neutral widgets. Widgets require a
matplotlib.axes.Axes object.
Here's a slider widget demo that ùpdates the amplitude of a sine curve. The update function is
triggered by the slider's on_changed() event.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.widgets import Slider
TWOPI = 2*np.pi
fig, ax = plt.subplots()
ax = plt.axis([0,TWOPI,-1,1])
def update(val):
# amp is the current value of the slider
amp = samp.val
# update curve
l.set_ydata(amp*np.sin(t))
# redraw canvas while idle
fig.canvas.draw_idle()
plt.show()
https://riptutorial.com/ 10
Other available widgets:
• AxesWidget
• Button
• CheckButtons
• Cursor
• EllipseSelector
• Lasso
• LassoSelector
• LockDraw
• MultiCursor
• RadioButtons
• RectangleSelector
• SpanSelector
• SubplotTool
• ToolHandles
https://riptutorial.com/ 11
This can be usefull when you want to visualize incoming data in real-time. This data could, for
example, come from a microcontroller that is continuously sampling an analog signal.
In this example we will get our data from a named pipe (also known as a fifo). For this example,
the data in the pipe should be numbers separted by newline characters, but you can adapt this to
your liking.
Example data:
100
123.5
1589
We will also be using the datatype deque, from the standard library collections. A deque object
works quite a lot like a list. But with a deque object it is quite easy to append something to it while
still keeping the deque object at a fixed length. This allows us to keep the x axis at a fixed length
instead of always growing and squishing the graph together. More information on deque objects
Choosing the right backend is vital for performance. Check what backends work on your operating
system, and choose a fast one. For me only qt4agg and the default backend worked, but the
default one was too slow. More information on backends in matplotlib
import matplotlib
import collections
#selecting the right backend, change qt4agg to your desired backend
matplotlib.use('qt4agg')
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def update(data):
line.set_ydata(data)
return line,
https://riptutorial.com/ 12
def data_gen():
while True:
"""
We read two data points in at once, to improve speed
You can read more at once to increase speed
Or you can read just one at a time for improved animation smoothness
data from the pipe comes in as a string,
and is seperated with a newline character,
which is why we use respectively eval and rstrip.
"""
datalist.append(eval((datapipe.readline()).rstrip('\n')))
datalist.append(eval((datapipe.readline()).rstrip('\n')))
yield datalist
If your plot starts to get delayed after a while, try adding more of the datalist.append data, so that
more lines get read each frame. Or choose a faster backend if you can.
https://riptutorial.com/ 13
Chapter 3: Basic Plots
Examples
Scatter Plots
# Data
x = [43,76,34,63,56,82,87,55,64,87,95,23,14,65,67,25,23,85]
y = [34,45,34,23,43,76,26,18,24,74,23,56,23,23,34,56,32,23]
https://riptutorial.com/ 14
# Create the Scatter Plot
ax.scatter(x, y,
color="blue", # Color of the dots
s=100, # Size of the dots
alpha=0.5, # Alpha/transparency of the dots (1 is opaque, 0 is transparent)
linewidths=1) # Size of edge around the dots
# Data
x = [21, 34, 44, 23]
y = [435, 334, 656, 1999]
labels = ["alice", "bob", "charlie", "diane"]
https://riptutorial.com/ 15
fig, ax = plt.subplots(1, figsize=(10, 6))
fig.suptitle('Example Of Labelled Scatterpoints')
Shaded Plots
https://riptutorial.com/ 16
import matplotlib.pyplot as plt
# Data
x = [0,1,2,3,4,5,6,7,8,9]
y1 = [10,20,40,55,58,55,50,40,20,10]
https://riptutorial.com/ 17
import matplotlib.pyplot as plt
# Data
x = [0,1,2,3,4,5,6,7,8,9]
y1 = [10,20,40,55,58,55,50,40,20,10]
y2 = [20,30,50,77,82,77,75,68,65,60]
Line plots
https://riptutorial.com/ 18
import matplotlib.pyplot as plt
# Data
x = [14,23,23,25,34,43,55,56,63,64,65,67,76,82,85,87,87,95]
y = [34,45,34,23,43,76,26,18,24,74,23,56,23,23,34,56,32,23]
Note that in general y is not a function of x and also that the values in x do not need to be sorted.
Here's how a line plot with unsorted x-values looks like:
https://riptutorial.com/ 19
Data plot
This is similar to a scatter plot, but uses the plot() function instead. The only difference in the
code here is the style argument.
plt.plot(x, y, 'b^')
# Create blue up-facing triangles
https://riptutorial.com/ 20
Data and line
The style argument can take symbols for both markers and line style:
plt.plot(x, y, 'go--')
# green circles and dashed line
https://riptutorial.com/ 21
Heatmap
Heatmaps are useful for visualizing scalar functions of two variables. They provide a “flat” image of
two-dimensional histograms (representing for instance the density of a certain area).
The following source code illustrates heatmaps using bivariate normally distributed numbers
centered at 0 in both directions (means [0.0, 0.0]) and a with a given covariance matrix. The data
is generated using the numpy function numpy.random.multivariate_normal; it is then fed to the
hist2d function of pyplot matplotlib.pyplot.hist2d.
https://riptutorial.com/ 22
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
https://riptutorial.com/ 23
# Plot a colorbar with label.
cb = plt.colorbar()
cb.set_label('Number of entries')
Here is the same data visualized as a 3D histogram (here we use only 20 bins for efficiency). The
code is based on this matplotlib demo.
https://riptutorial.com/ 24
N_numbers = 100000
N_bins = 20
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
hist, xedges, yedges = np.histogram2d(x, y, bins=N_bins)
https://riptutorial.com/ 25
Chapter 4: Boxplots
Examples
Basic Boxplots
Boxplots are descriptive diagrams that help to compare the distribution of different series of data.
They are descriptive because they show measures (e.g. the median) which do not assume an
underlying probability distribution.
The most basic example of a boxplot in matplotlib can be achieved by just passing the data as a
list of lists:
dataline1 = [43,76,34,63,56,82,87,55,64,87,95,23,14,65,67,25,23,85]
dataline2 = [34,45,34,23,43,76,26,18,24,74,23,56,23,23,34,56,32,23]
data = [ dataline1, dataline2 ]
plt.boxplot( data )
However, it is a common practice to use numpy arrays as parameters to the plots, since they are
often the result of previous calculations. This can be done as follows:
import numpy as np
import matplotlib as plt
np.random.seed(123)
dataline1 = np.random.normal( loc=50, scale=20, size=18 )
dataline2 = np.random.normal( loc=30, scale=10, size=18 )
data = np.stack( [ dataline1, dataline2 ], axis=1 )
plt.boxplot( data )
https://riptutorial.com/ 26
Read Boxplots online: https://riptutorial.com/matplotlib/topic/6086/boxplots
https://riptutorial.com/ 27
Chapter 5: Boxplots
Examples
Boxplot function
Matplotlib has its own implementation of boxplot. The relevant aspects of this function is that, by
default, the boxplot is showing the median (percentile 50%) with a red line. The box represents Q1
and Q3 (percentiles 25 and 75), and the whiskers give an idea of the range of the data (possibly at
Q1 - 1.5IQR; Q3 + 1.5IQR; being IQR the interquartile range, but this lacks confirmation). Also
notice that samples beyond this range are shown as markers (these are named fliers).
NOTE: Not all implementations of boxplot follow the same rules. Perhaps the most
common boxplot diagram uses the whiskers to represent the minimum and maximum
(making fliers non-existent). Also notice that this plot is sometimes called box-and-
whisker plot and box-and-whisker diagram.
The following recipe show some of the things you can do with the current matplotlib
implementation of boxplot:
X1 = np.random.normal(0, 1, 500)
X2 = np.random.normal(0.3, 1, 500)
https://riptutorial.com/ 28
1. Default matplotlib boxplot
https://riptutorial.com/ 29
2. Changing some features of the boxplot using function arguments
https://riptutorial.com/ 30
3. Multiple boxplot in the same plot window
https://riptutorial.com/ 31
4. Hidding some features of the boxplot
https://riptutorial.com/ 32
5. Advanced customization of a boxplot using props
If you intend to do some advanced customization of your boxplot you should know that the props
dictionaries you build (for example):
...refer mostly (if not all) to Line2D objects. This means that only arguments available in that class
are changeable. You will notice the existence of keywords such as whiskerprops, boxprops,
flierprops, and capprops. These are the elements you need to provide a props dictionary to further
customize it.
NOTE: Further customization of the boxplot using this implementation might prove
difficult. In some instances the use of other matplotlib elements such as patches to
https://riptutorial.com/ 33
build ones own boxplot can be advantageous (considerable changes to the box
element, for example).
https://riptutorial.com/ 34
Chapter 6: Closing a figure window
Syntax
• plt.close() # closes the current active figure
• plt.close(fig) # closes the figure with handle 'fig'
• plt.close(num) # closes the figure number 'num'
• plt.close(name) # closes the figure with the label 'name'
• plt.close('all') # closes all figures
Examples
Closing the current active figure using pyplot
The pyplot interface to matplotlib might be the simplest way to close a figure.
https://riptutorial.com/ 35
Chapter 7: Colormaps
Examples
Basic usage
Using built-in colormaps is as simple as passing the name of the required colormap (as given in
the colormaps reference) to the plotting function (such as pcolormesh or contourf) that expects it,
usually in the form of a cmap keyword argument:
plt.figure()
plt.pcolormesh(np.random.rand(20,20),cmap='hot')
plt.show()
https://riptutorial.com/ 36
Colormaps are especially useful for visualizing three-dimensional data on two-dimensional plots,
but a good colormap can also make a proper three-dimensional plot much clearer:
ax1.set_zlim([-1,1])
ax1.set_zlabel(r'$\cos(\pi x) \sin(\p i y)$')
plt.show()
https://riptutorial.com/ 37
Using custom colormaps
Apart from the built-in colormaps defined in the colormaps reference (and their reversed maps,
with '_r' appended to their name), custom colormaps can also be defined. The key is the
matplotlib.cm module.
The below example defines a very simple colormap using cm.register_cmap, containing a single
colour, with the opacity (alpha value) of the colour interpolating between fully opaque and fully
transparent in the data range. Note that the important lines from the point of view of the colormap
are the import of cm, the call to register_cmap, and the passing of the colormap to plot_surface.
https://riptutorial.com/ 38
# define custom colormap with fixed colour and alpha gradient
# use simple linear interpolation in the entire scale
cm.register_cmap(name='alpha_gradient',
data={'red': [(0.,0,0),
(1.,0,0)],
'green': [(0.,0.6,0.6),
(1.,0.6,0.6)],
'blue': [(0.,0.4,0.4),
(1.,0.4,0.4)],
'alpha': [(0.,1,1),
(1.,0,0)]})
# plot sphere with custom colormap; constrain mapping to between |z|=0.7 for enhanced effect
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(x,y,z,cmap='alpha_gradient',vmin=-
0.7,vmax=0.7,rstride=1,cstride=1,linewidth=0.5,edgecolor='b')
ax.set_xlim([-1,1])
ax.set_ylim([-1,1])
ax.set_zlim([-1,1])
ax.set_aspect('equal')
plt.show()
https://riptutorial.com/ 39
In more complicated scenarios, one can define a list of R/G/B(/A) values into which matplotlib
interpolates linearly in order to determine the colours used in the corresponding plots.
The original default colourmap of MATLAB (replaced in version R2014b) called jet is ubiquitous
due to its high contrast and familiarity (and was the default of matplotlib for compatibility reasons).
Despite its popularity, traditional colormaps often have deficiencies when it comes to representing
data accurately. The percieved change in these colormaps does not correspond to changes in
data; and a conversion of the colormap to greyscale (by, for instance, printing a figure using a
black-and-white printer) might cause loss of information.
Perceptually uniform colormaps have been introduced to make data visualization as accurate and
accessible as possible. Matplotlib introduced four new, perceptually uniform colormaps in version
1.5, with one of them (named viridis) to be the default from version 2.0. These four colormaps (
viridis, inferno, plasma and magma) are all optimal from the point of view of perception, and these
should be used for data visualization by default unless there are very good reasons not to do so.
These colormaps introduce as little bias as possible (by not creating features where there aren't
https://riptutorial.com/ 40
any to begin with), and they are suitable for an audience with reduced color perception.
As an example for visually distorting data, consider the following two top-view plots of pyramid-like
objects:
Which one of the two is a proper pyramid? The answer is of course that both of them are, but this
is far from obvious from the plot using the jet colormap:
https://riptutorial.com/ 41
This feature is at the core of perceptual uniformity.
If you have predefined ranges and want to use specific colors for those ranges you can declare
custom colormap. For example:
x = np.linspace(-2,2,500)
y = np.linspace(-2,2,500)
XX, YY = np.meshgrid(x, y)
Z = np.sin(XX) * np.cos(YY)
https://riptutorial.com/ 42
plt.pcolormesh(x,y,Z, cmap=cmap, norm=norm)
plt.colorbar()
plt.show()
Produces
Color i will be used for values between boundary i and i+1. Colors can be specified by names (
'red', 'green'), HTML codes ('#ffaa44', '#441188') or RGB tuples ((0.2, 0.9, 0.45)).
https://riptutorial.com/ 43
Chapter 8: Contour Maps
Examples
Simple filled contour plotting
Result:
https://riptutorial.com/ 44
Simple contour plotting
Result:
https://riptutorial.com/ 45
Chapter 9: Coordinates Systems
Remarks
Matplotlib has four distinct coordinate systems which can be leveraged to ease the positioning of
different object, e.g., text. Each system has a corresponding transformation object which transform
coordinates from that system to the so called display coordinate system.
Data coordinate system is the system defined by the data on the respective axes. It is useful
when trying to position some object relative to the data plotted. The range is given by the xlim and
ylim properties of Axes. Its corresponding transformation object is ax.transData.
Axes coordinate system is the system tied to its Axes object. Points (0, 0) and (1, 1) define the
bottom-left and top-right corners of the axes. As such it is useful when positioning relative to the
axes, like top-center of the plot. Its corresponding transformation object is ax.transAxes.
Figure coordinate system is analogous to the axes coordinate system, except that it is tied to the
Figure. Points (0, 0) and (1, 1) represent the bottom-left and top-right corners of the figure. It is
useful when trying to position something relative to the whole image. Its corresponding
transformation object is fig.transFigure.
Display coordinate system is the system of the image given in pixels. Points (0, 0) and (width,
height) are the bottom-left and top-right pixels of image or display. It can be used for positioning
absolutely. Since transformation objects transform coordinates into this coordinate system, display
system has no transformation object associated with it. However, None or
matplotlib.transforms.IdentityTransform() can be used when necessary.
https://riptutorial.com/ 46
More details are available here.
Examples
Coordinate systems and text
The coordinate systems of Matplotlib come very handy when trying to annotate the plots you
make. Sometimes you would like to position text relatively to your data, like when trying to label a
specific point. Other times you would maybe like to add a text on top of the figure. This can easily
be achieved by selecting an appropriate coordinate system by passing a transformation object to
the transform parameter in call to text().
fig, ax = plt.subplots()
https://riptutorial.com/ 47
2., 3., 'important point', # x, y, text,
ha='center', va='bottom', # text alignment,
transform=ax.transData # coordinate system transformation
)
plt.text( # position text relative to Axes
1.0, 1.0, 'axes corner',
ha='right', va='top',
transform=ax.transAxes
)
plt.text( # position text relative to Figure
0.0, 1.0, 'figure corner',
ha='left', va='top',
transform=fig.transFigure
)
plt.text( # position text absolutely at specific pixel on image
200, 300, 'pixel (200, 300)',
ha='center', va='center',
transform=None
)
plt.show()
https://riptutorial.com/ 48
Read Coordinates Systems online: https://riptutorial.com/matplotlib/topic/4566/coordinates-
systems
https://riptutorial.com/ 49
Chapter 10: Figures and Axes Objects
Examples
Creating a figure
The figure contains all the plot elements. The main way to create a figure in matplotlib is to use
pyplot.
You can optionally supply a number, which you can use to access a previously-created figure. If a
number is not supplied, the last-created figure's ID will be incremented and used instead; figures
are indexed starting from 1, not 0.
Instead of a number, figures can also identified by a string. If using an interactive backend, this will
also set the window title.
plt.figure(fig.number) # or
plt.figure(1)
Creating an axes
There are two main ways to create an axes in matplotlib: using pyplot, or using the object-oriented
API.
Using pyplot:
fig = plt.figure()
https://riptutorial.com/ 50
ax = fig.add_subplot(3, 2, 1)
The convenience function plt.subplots() can be used to produce a figure and collection of
subplots in one command:
https://riptutorial.com/ 51
Chapter 11: Grid Lines and Tick Marks
Examples
Plot With Gridlines
# The Data
x = [1, 2, 3, 4]
y = [234, 124,368, 343]
https://riptutorial.com/ 52
fig.suptitle('Example Of Plot With Grid Lines')
plt.show()
# The Data
x = [1, 2, 3, 4]
y = [234, 124,368, 343]
https://riptutorial.com/ 53
fig, ax = plt.subplots(1, figsize=(8, 6))
fig.suptitle('Example Of Plot With Major and Minor Grid Lines')
# Show the minor grid lines with very faint and almost transparent grey lines
plt.minorticks_on()
plt.grid(b=True, which='minor', color='#999999', linestyle='-', alpha=0.2)
plt.show()
https://riptutorial.com/ 54
Chapter 12: Histogram
Examples
Simple histogram
plt.hist(data)
plt.show()
https://riptutorial.com/ 55
Chapter 13: Image manipulation
Examples
Opening images
Images are read from file (.png only) with the imread function:
img = mpimg.imread('my_image.png')
plt.imshow(img)
https://riptutorial.com/ 56
Read Image manipulation online: https://riptutorial.com/matplotlib/topic/4575/image-manipulation
https://riptutorial.com/ 57
Chapter 14: Integration with TeX/LaTeX
Remarks
• Matplotlib’s LaTeX support requires a working LaTeX installation, dvipng (which may be
included with your LaTeX installation), and Ghostscript (GPL Ghostscript 8.60 or later is
recommended).
• Matplotlib’s pgf support requires a recent LaTeX installation that includes the TikZ/PGF
packages (such as TeXLive), preferably with XeLaTeX or LuaLaTeX installed.
Examples
Inserting TeX formulae in plots
TeX uses the backslash \ for commands and symbols, which can conflict with special characters
in Python strings. In order to use literal backslashes in a Python string, they must either be
escaped or incorporated in a raw string:
plt.xlabel('\\alpha')
plt.xlabel(r'\alpha')
https://riptutorial.com/ 58
can be produced by the code
https://riptutorial.com/ 59
Note, however, the warning in the example matplotlibrc file:
In order to include plots created with matplotlib in TeX documents, they should be saved as pdf or
eps files. In this way, any text in the plot (including TeX formulae) is rendered as text in the final
document.
Plots in matplotlib can be exported to TeX code using the pgf macro package to display graphics.
\usepackage{pgf}
https://riptutorial.com/ 60
\input{my_pgf_plot.pgf}
https://riptutorial.com/ 61
Chapter 15: Legends
Examples
Simple Legend
Suppose you have multiple lines in the same plot, each of a different color, and you wish to make
a legend to tell what each line represents. You can do this by passing on a label to each of the
lines when you call plot(), e.g., the following line will be labelled "My Line 1".
This specifies the text that will appear in the legend for that line. Now to make the actual legend
visible, we can call ax.legend()
By default it will create a legend inside a box on the upper right hand corner of the plot. You can
pass arguments to legend() to customize it. For instance we can position it on the lower right hand
corner, with out a frame box surrounding it, and creating a title for the legend by calling the
following:
Below is an example:
https://riptutorial.com/ 62
import matplotlib.pyplot as plt
# The data
x = [1, 2, 3]
y1 = [2, 15, 27]
y2 = [10, 40, 45]
y3 = [5, 25, 40]
# Draw all the lines in the same plot, assigning a label for each one to be
# shown in the legend
ax.plot(x, y1, color="red", label="My Line 1")
ax.plot(x, y2, color="green", label="My Line 2")
ax.plot(x, y3, color="blue", label="My Line 3")
# Add a legend with title, position it on the lower right (loc) with no box framing (frameon)
ax.legend(loc="lower right", title="Legend Title", frameon=False)
https://riptutorial.com/ 63
# Show the plot
plt.show()
Sometimes it is necessary or desirable to place the legend outside the plot. The following code
shows how to do it.
# The data
x = [1, 2, 3]
y1 = [1, 2, 4]
y2 = [2, 4, 8]
y3 = [3, 5, 14]
https://riptutorial.com/ 64
# Create the lines, assigning different colors for each one.
# Also store the created line objects
l1 = ax.plot(x, y1, color="red")[0]
l2 = ax.plot(x, y2, color="green")[0]
l3 = ax.plot(x, y3, color="blue")[0]
# Adjust the scaling factor to fit your legend text completely outside the plot
# (smaller value results in more space being made for the legend)
plt.subplots_adjust(right=0.85)
plt.show()
Another way to place the legend outside the plot is to use bbox_to_anchor + bbox_extra_artists +
bbox_inches='tight', as shown in the example below:
https://riptutorial.com/ 65
https://riptutorial.com/ 66
instead of creating a legend at the axes level (which will create a separate legend for each
subplot). This is achieved by calling fig.legend() as can be seen in the code for the following
code.
# The data
x = [1, 2, 3]
y1 = [1, 2, 3]
y2 = [3, 1, 3]
y3 = [1, 3, 1]
y4 = [2, 2, 3]
# Adjust the scaling factor to fit your legend text completely outside the plot
# (smaller value results in more space being made for the legend)
plt.subplots_adjust(right=0.85)
plt.show()
When plot() is called, it returns a list of line2D objects. In this case it just returns a list with one
single line2D object, which is extracted with the [0] indexing, and stored in l1.
A list of all the line2D objects that we are interested in including in the legend need to be passed
on as the first argument to fig.legend(). The second argument to fig.legend() is also necessary. It
is supposed to be a list of strings to use as the labels for each line in the legend.
The other arguments passed on to fig.legend() are purely optional, and just help with fine-tuning
the aesthetics of the legend.
If you call plt.legend() or ax.legend() more than once, the first legend is removed and a new one
https://riptutorial.com/ 67
is drawn. According the official documentation:
This has been done so that it is possible to call legend() repeatedly to update the
legend to the latest handles on the Axes
Fear not, though: It is still quite simple to add a second legend (or third, or fourth...) to an axes. In
the example here, we plot two lines, then plot markers on their respective maxima and minima.
One legend is for the lines, and the other is for the markers.
https://riptutorial.com/ 68
The key is to make sure you have references to the legend objects. The first one you instantiate (
leg1) is removed from the figure when you add the second one, but the leg1 object still exists and
can be added back with ax.add_artist.
The really great thing is that you can can still manipulate both legends. For example, add the
following to the bottom of the above code:
leg1.get_lines()[0].set_lw(8)
leg2.get_texts()[1].set_color('b')
Finally, it's worth mentioning that in the example only the lines were given labels when plotted,
https://riptutorial.com/ 69
meaning that ax.legend() adds only those lines to the leg1. The legend for the markers (leg2)
therefore required the lines and labels as arguments when it was instantiated. We could have,
alternatively, given labels to the markers when they were plotted too. But then both calls to
ax.legend would have required some extra arguments so that each legend contained only the
items we wanted.
https://riptutorial.com/ 70
Chapter 16: LogLog Graphing
Introduction
LogLog graphing is a possibility to illustrate an exponential function in a linear way.
Examples
LogLog graphing
Let y(x) = A * x^a, for example A=30 and a=3.5. Taking the natural logarithm (ln) of both sides
yields (using the common rules for logarithms): ln(y) = ln(A * x^a) = ln(A) + ln(x^a) = ln(A) + a *
ln(x). Thus, a plot with logarithmic axes for both x and y will be a linear curve. The slope of this
curve is the exponent a of y(x), while the y-intercept y(0) is the natural logarithm of A, ln(A) =
ln(30) = 3.401.
The following example illustrates the relation between an exponential function and the linear loglog
plot (the function is y = A * x^a with A=30 and a=3.5):
import numpy as np
import matplotlib.pyplot as plt
A = 30
a = 3.5
x = np.linspace(0.01, 5, 10000)
y = A * x**a
ax = plt.gca()
plt.plot(x, y, linewidth=2.5, color='navy', label=r'$f(x) = 30 \cdot x^{3.5}$')
plt.legend(loc='upper left')
plt.xlabel(r'x')
plt.ylabel(r'y')
ax.grid(True)
plt.title(r'Normal plot')
plt.show()
plt.clf()
xlog = np.log(x)
ylog = np.log(y)
ax = plt.gca()
plt.plot(xlog, ylog, linewidth=2.5, color='navy', label=r'$f(x) = 3.5\cdot x + \ln(30)$')
plt.legend(loc='best')
plt.xlabel(r'log(x)')
plt.ylabel(r'log(y)')
ax.grid(True)
plt.title(r'Log-Log plot')
plt.show()
plt.clf()
https://riptutorial.com/ 71
https://riptutorial.com/ 72
Read LogLog Graphing online: https://riptutorial.com/matplotlib/topic/10145/loglog-graphing
https://riptutorial.com/ 73
Chapter 17: Multiple Plots
Syntax
• List item
Examples
Grid of Subplots using subplot
"""
================================================================================
CREATE A 2 BY 2 GRID OF SUB-PLOTS WITHIN THE SAME FIGURE.
================================================================================
"""
import matplotlib.pyplot as plt
https://riptutorial.com/ 74
# The data
x = [1,2,3,4,5]
y1 = [0.59705847, 0.25786401, 0.63213726, 0.63287317, 0.73791151]
y2 = [1.19411694, 0.51572803, 1.26427451, 1.26574635, 1.47582302]
y3 = [0.86793828, 0.07563408, 0.67670068, 0.78932712, 0.0043694]
# 5 more random values
y4 = [0.43396914, 0.03781704, 0.33835034, 0.39466356, 0.0021847]
# Initialise the figure and a subplot axes. Each subplot sharing (showing) the
# same range of values for the x and y axis in the plots.
fig, axes = plt.subplots(2, 2, figsize=(8, 6), sharex=True, sharey=True)
plt.show()
https://riptutorial.com/ 75
"""
================================================================================
DRAW MULTIPLE LINES IN THE SAME PLOT
================================================================================
"""
import matplotlib.pyplot as plt
# The data
x = [1, 2, 3, 4, 5]
y1 = [2, 15, 27, 35, 40]
y2 = [10, 40, 45, 47, 50]
y3 = [5, 25, 40, 45, 47]
# Draw all the lines in the same plot, assigning a label for each one to be
# shown in the legend.
ax.plot(x, y1, color="red", label="My Line 1")
ax.plot(x, y2, color="green", label="My Line 2")
https://riptutorial.com/ 76
ax.plot(x, y3, color="blue", label="My Line 3")
plt.show()
The gridspec package allows more control over the placement of subplots. It makes it much easier
to control the margins of the plots and the spacing between the individual subplots. In addition, it
allows for different sized axes on the same figure by defining axes which take up multiple grid
locations.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
fig = plt.figure(0)
fig.clf()
https://riptutorial.com/ 77
A plot of 2 functions on shared x-axis.
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(111)
https://riptutorial.com/ 78
# create line plot of y2(x)
line2, = ax2.plot(x, y2, 'r', label="Function y2")
ax2.set_ylabel('y2', color='r')
plt.show()
https://riptutorial.com/ 79
https://riptutorial.com/ 80
import matplotlib
matplotlib.use("TKAgg")
https://riptutorial.com/ 81
# module to allow user to select csv file
from tkinter.filedialog import askopenfilename
#==============================================================================
# User chosen Data for plots
#==============================================================================
#==============================================================================
# Plots on two different Figures and sets the size of the figures
#==============================================================================
#------------------------------------------------------------------------------
# Figure 1 with 6 plots
#------------------------------------------------------------------------------
# plot one
# Plot column labeled TIME from csv file and color it red
# subplot(2 Rows, 3 Columns, First subplot,)
ax1 = f1.add_subplot(2,3,1)
ax1.plot(data[["TIME"]], label = 'Curve 1', color = "r", marker = '^', markevery = 10)
# added line marker triangle
# plot two
# plot column labeled TIME from csv file and color it green
# subplot(2 Rows, 3 Columns, Second subplot)
ax2 = f1.add_subplot(2,3,2)
ax2.plot(data[["TIME"]], label = 'Curve 2', color = "g", marker = '*', markevery = 10)
# added line marker star
# plot three
# plot column labeled TIME from csv file and color it blue
# subplot(2 Rows, 3 Columns, Third subplot)
ax3 = f1.add_subplot(2,3,3)
ax3.plot(data[["TIME"]], label = 'Curve 3', color = "b", marker = 'D', markevery = 10)
# added line marker diamond
# plot four
# plot column labeled TIME from csv file and color it purple
# subplot(2 Rows, 3 Columns, Fourth subplot)
ax4 = f1.add_subplot(2,3,4)
ax4.plot(data[["TIME"]], label = 'Curve 4', color = "#800080")
https://riptutorial.com/ 82
# plot five
# plot column labeled TIME from csv file and color it cyan
# subplot(2 Rows, 3 Columns, Fifth subplot)
ax5 = f1.add_subplot(2,3,5)
ax5.plot(data[["TIME"]], label = 'Curve 5', color = "c")
# plot six
# plot column labeled TIME from csv file and color it black
# subplot(2 Rows, 3 Columns, Sixth subplot)
ax6 = f1.add_subplot(2,3,6)
ax6.plot(data[["TIME"]], label = 'Curve 6', color = "k")
#------------------------------------------------------------------------------
# Figure 2 with 6 plots
#------------------------------------------------------------------------------
# plot one
# Curve 1: plot column labeled Acceleration from csv file and color it red
# Curve 2: plot column labeled TIME from csv file and color it green
# subplot(2 Rows, 3 Columns, First subplot)
ax10 = f2.add_subplot(2,3,1)
ax10.plot(data[["Acceleration"]], label = 'Curve 1', color = "r")
ax10.plot(data[["TIME"]], label = 'Curve 7', color="g", linestyle ='--')
# dashed line
# plot two
# Curve 1: plot column labeled Acceleration from csv file and color it green
# Curve 2: plot column labeled TIME from csv file and color it black
# subplot(2 Rows, 3 Columns, Second subplot)
ax20 = f2.add_subplot(2,3,2)
ax20.plot(data[["Acceleration"]], label = 'Curve 2', color = "g")
ax20.plot(data[["TIME"]], label = 'Curve 8', color = "k", linestyle ='-')
# solid line (default)
# plot three
# Curve 1: plot column labeled Acceleration from csv file and color it blue
# Curve 2: plot column labeled TIME from csv file and color it purple
# subplot(2 Rows, 3 Columns, Third subplot)
ax30 = f2.add_subplot(2,3,3)
ax30.plot(data[["Acceleration"]], label = 'Curve 3', color = "b")
ax30.plot(data[["TIME"]], label = 'Curve 9', color = "#800080", linestyle ='-.')
# dash_dot line
# plot four
# Curve 1: plot column labeled Acceleration from csv file and color it purple
# Curve 2: plot column labeled TIME from csv file and color it red
# subplot(2 Rows, 3 Columns, Fourth subplot)
ax40 = f2.add_subplot(2,3,4)
ax40.plot(data[["Acceleration"]], label = 'Curve 4', color = "#800080")
ax40.plot(data[["TIME"]], label = 'Curve 10', color = "r", linestyle =':')
# dotted line
# plot five
# Curve 1: plot column labeled Acceleration from csv file and color it cyan
# Curve 2: plot column labeled TIME from csv file and color it blue
# subplot(2 Rows, 3 Columns, Fifth subplot)
https://riptutorial.com/ 83
ax50 = f2.add_subplot(2,3,5)
ax50.plot(data[["Acceleration"]], label = 'Curve 5', color = "c")
ax50.plot(data[["TIME"]], label = 'Curve 11', color = "b", marker = 'o', markevery = 10)
# added line marker circle
# plot six
# Curve 1: plot column labeled Acceleration from csv file and color it black
# Curve 2: plot column labeled TIME from csv file and color it cyan
# subplot(2 Rows, 3 Columns, Sixth subplot)
ax60 = f2.add_subplot(2,3,6)
ax60.plot(data[["Acceleration"]], label = 'Curve 6', color = "k")
ax60.plot(data[["TIME"]], label = 'Curve 12', color = "c", marker = 's', markevery = 10)
# added line marker square
#==============================================================================
# Figure Plot options
#==============================================================================
#------------------------------------------------------------------------------
# Figure 1 options
#------------------------------------------------------------------------------
https://riptutorial.com/ 84
ax4.set_ylim([0,20])
#------------------------------------------------------------------------------
# Figure 2 options
#------------------------------------------------------------------------------
https://riptutorial.com/ 85
ax40.set_ylim([-20,20])
#==============================================================================
# User chosen file location Save PDF
#==============================================================================
pdf.close()
#==============================================================================
# Show plot
#==============================================================================
# manually set the subplot spacing when there are multiple plots
#plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace =None, hspace=None )
plt.show()
https://riptutorial.com/ 86
Chapter 18: Three-dimensional plots
Remarks
Three-dimensional plotting in matplotlib has historically been a bit of a kludge, as the rendering
engine is inherently 2d. The fact that 3d setups are rendered by plotting one 2d chunk after the
other implies that there are often rendering issues related to the apparent depth of objects. The
core of the problem is that two non-connected objects can either be fully behind, or fully in front of
one another, which leads to artifacts as shown in the below figure of two interlocked rings (click for
animated gif):
This can however be fixed. This artefact only exists when plotting multiple surfaces on the same
plot - as each is rendered as a flat 2D shape, with a single parameter determining the view
distance. You will notice that a single complicated surface does not suffer the same problem.
The way to remedy this is to join the plot objects together using transparent bridges:
https://riptutorial.com/ 87
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from scipy.special import erf
fig = plt.figure()
ax = fig.gca(projection='3d')
X = np.arange(0, 6, 0.25)
Y = np.arange(0, 6, 0.25)
X, Y = np.meshgrid(X, Y)
Z1 = np.empty_like(X)
Z2 = np.empty_like(X)
C1 = np.empty_like(X, dtype=object)
C2 = np.empty_like(X, dtype=object)
for i in range(len(X)):
for j in range(len(X[0])):
z1 = 0.5*(erf((X[i,j]+Y[i,j]-4.5)*0.5)+1)
z2 = 0.5*(erf((-X[i,j]-Y[i,j]+4.5)*0.5)+1)
Z1[i,j] = z1
Z2[i,j] = z2
# Join the two surfaces flipping one of them (using also the bridge)
X_full = np.vstack([X, X_bridge, np.flipud(X)])
Y_full = np.vstack([Y, Y_bridge, np.flipud(Y)])
Z_full = np.vstack([Z1, Z_bridge, np.flipud(Z2)])
color_full = np.vstack([C1, color_bridge, np.flipud(C2)])
plt.show()
https://riptutorial.com/ 88
https://riptutorial.com/ 89
Examples
Creating three-dimensional axes
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
Beside the straightforward generalizations of two-dimensional plots (such as line plots, scatter
plots, bar plots, contour plots), several surface plotting methods are available, for instance
ax.plot_surface:
https://riptutorial.com/ 90
# generate example data
import numpy as np
x,y = np.meshgrid(np.linspace(-1,1,15),np.linspace(-1,1,15))
z = np.cos(x*np.pi)*np.sin(y*np.pi)
https://riptutorial.com/ 91
Credits
S.
Chapters Contributors
No
Getting started with Amitay Stern, ChaoticTwist, Chr, Chris Mueller, Community,
1
matplotlib dermen, evtoh, farenorth, Josh, jrjc, pmos, Serenity, tacaswell
Animations and
2 FiN, smurfendrek123, user2314737
interactive plotting
4 Boxplots Luis
Closing a figure
5 Brian, David Zwicker
window
Coordinates
8 jure
Systems
Integration with
13 Andras Deak, Bosoneando, Chris Mueller, Næreen, Serenity
TeX/LaTeX
Three-dimensional
17 Andras Deak, Serenity, will
plots
https://riptutorial.com/ 92