Matplotlib tutorial for beginner

Related tags

python tutorial matplotlib

Matplotlib tutorial

Nicolas P. Rougier

Sources are available from github

All code and material is licensed under a Creative Commons Attribution-ShareAlike 4.0.

You can test your installation before the tutorial using the script.

See also:


matplotlib is probably the single most used Python package for 2D-graphics. It provides both a very quick way to visualize data from Python and publication-quality figures in many formats. We are going to explore matplotlib in interactive mode covering most common cases.

IPython and the pylab mode

IPython is an enhanced interactive Python shell that has lots of interesting features including named inputs and outputs, access to shell commands, improved debugging and much more. When we start it with the command line argument -pylab (--pylab since IPython version 0.12), it allows interactive matplotlib sessions that have Matlab/Mathematica-like functionality.


pyplot provides a convenient interface to the matplotlib object-oriented plotting library. It is modeled closely after Matlab(TM). Therefore, the majority of plotting commands in pyplot have Matlab(TM) analogs with similar arguments. Important commands are explained with interactive examples.

Simple plot

In this section, we want to draw the cosine and sine functions on the same plot. Starting from the default settings, we'll enrich the figure step by step to make it nicer.

The first step is to get the data for the sine and cosine functions:

import numpy as np

X = np.linspace(-np.pi, np.pi, 256, endpoint=True)
C, S = np.cos(X), np.sin(X)

X is now a NumPy array with 256 values ranging from -π to +π (included). C is the cosine (256 values) and S is the sine (256 values).

To run the example, you can download each of the examples and run it using:

$ python

You can get source for each step by clicking on the corresponding figure.

Using defaults


Matplotlib comes with a set of default settings that allow customizing all kinds of properties. You can control the defaults of almost every property in matplotlib: figure size and dpi, line width, color and style, axes, axis and grid properties, text and font properties and so on. While matplotlib defaults are rather good in most cases, you may want to modify some properties for specific cases.

Instantiating defaults



In the script below, we've instantiated (and commented) all the figure settings that influence the appearance of the plot. The settings have been explicitly set to their default values, but now you can interactively play with the values to explore their affect (see Line properties and Line styles below).

Changing colors and line widths


As a first step, we want to have the cosine in blue and the sine in red and a slightly thicker line for both of them. We'll also slightly alter the figure size to make it more horizontal.

plt.figure(figsize=(10,6), dpi=80)
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-")
plt.plot(X, S, color="red",  linewidth=2.5, linestyle="-")

Setting limits


Current limits of the figure are a bit too tight and we want to make some space in order to clearly see all data points.

plt.xlim(X.min()*1.1, X.max()*1.1)
plt.ylim(C.min()*1.1, C.max()*1.1)

Setting ticks


Current ticks are not ideal because they do not show the interesting values (+/-π,+/-π/2) for sine and cosine. We'll change them such that they show only these values.

plt.xticks( [-np.pi, -np.pi/2, 0, np.pi/2, np.pi])
plt.yticks([-1, 0, +1])

Setting tick labels


Ticks are now properly placed but their label is not very explicit. We could guess that 3.142 is π but it would be better to make it explicit. When we set tick values, we can also provide a corresponding label in the second argument list. Note that we'll use latex to allow for nice rendering of the label.

plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],
       [r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$'])

plt.yticks([-1, 0, +1],
       [r'$-1$', r'$0$', r'$+1$'])

Moving spines


Spines are the lines connecting the axis tick marks and noting the boundaries of the data area. They can be placed at arbitrary positions and until now, they were on the border of the axis. We'll change that since we want to have them in the middle. Since there are four of them (top/bottom/left/right), we'll discard the top and right by setting their color to none and we'll move the bottom and left ones to coordinate 0 in data space coordinates.

ax = plt.gca()

Adding a legend


Let's add a legend in the upper left corner. This only requires adding the keyword argument label (that will be used in the legend box) to the plot commands.

plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine")
plt.plot(X, S, color="red",  linewidth=2.5, linestyle="-", label="sine")

plt.legend(loc='upper left', frameon=False)

Annotate some points


Let's annotate some interesting points using the annotate command. We choose the 2π/3 value and we want to annotate both the sine and the cosine. We'll first draw a marker on the curve as well as a straight dotted line. Then, we'll use the annotate command to display some text with an arrow.


t = 2*np.pi/3
plt.plot([t,t],[0,np.cos(t)], color ='blue', linewidth=1.5, linestyle="--")
plt.scatter([t,],[np.cos(t),], 50, color ='blue')

             xy=(t, np.sin(t)), xycoords='data',
             xytext=(+10, +30), textcoords='offset points', fontsize=16,
             arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))

plt.plot([t,t],[0,np.sin(t)], color ='red', linewidth=1.5, linestyle="--")
plt.scatter([t,],[np.sin(t),], 50, color ='red')

             xy=(t, np.cos(t)), xycoords='data',
             xytext=(-90, -50), textcoords='offset points', fontsize=16,
             arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))

Devil is in the details



The tick labels are now hardly visible because of the blue and red lines. We can make them bigger and we can also adjust their properties such that they'll be rendered on a semi-transparent white background. This will allow us to see both the data and the labels.

for label in ax.get_xticklabels() + ax.get_yticklabels():
    label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.65 ))

Figures, Subplots, Axes and Ticks

So far we have used implicit figure and axes creation. This is handy for fast plots. We can have more control over the display using figure, subplot, and axes explicitly. A figure in matplotlib means the whole window in the user interface. Within this figure there can be subplots. While subplot positions the plots in a regular grid, axes allows free placement within the figure. Both can be useful depending on your intention. We've already worked with figures and subplots without explicitly calling them. When we call plot, matplotlib calls gca() to get the current axes and gca in turn calls gcf() to get the current figure. If there is none it calls figure() to make one, strictly speaking, to make a subplot(111). Let's look at the details.


A figure is the windows in the GUI that has "Figure #" as title. Figures are numbered starting from 1 as opposed to the normal Python way starting from 0. This is clearly MATLAB-style. There are several parameters that determine what the figure looks like:

Argument Default Description
num 1 number of figure
figsize figure.figsize figure size in in inches (width, height)
dpi figure.dpi resolution in dots per inch
facecolor figure.facecolor color of the drawing background
edgecolor figure.edgecolor color of edge around the drawing background
frameon True draw figure frame or not

The defaults can be specified in the resource file and will be used most of the time. Only the number of the figure is frequently changed.

When you work with the GUI you can close a figure by clicking on the x in the upper right corner. You can also close a figure programmatically by calling close. Depending on the argument it closes (1) the current figure (no argument), (2) a specific figure (figure number or figure instance as argument), or (3) all figures (all as argument).

As with other objects, you can set figure properties with the set_something methods.


With subplot you can arrange plots in a regular grid. You need to specify the number of rows and columns and the number of the plot. Note that the gridspec command is a more powerful alternative.

figures/subplot-horizontal.png figures/subplot-vertical.png figures/subplot-grid.png figures/gridspec.png


Axes are very similar to subplots but allow placement of plots at any location in the figure. So if we want to put a smaller plot inside a bigger one we do so with axes.

figures/axes.png figures/axes-2.png


Well formatted ticks are an important part of publishing-ready figures. Matplotlib provides a totally configurable system for ticks. There are tick locators to specify where ticks should appear and tick formatters to give ticks the appearance you want. Major and minor ticks can be located and formatted independently from each other. By default minor ticks are not shown, i.e. there is only an empty list for them because it is as NullLocator (see below).

Tick Locators

There are several locators for different kind of requirements:

Class Description

No ticks.


Place a tick on every multiple of some base number of points plotted.


Tick locations are fixed.


Determine the tick locations.


Set a tick on every integer that is multiple of some base.


Select no more than n intervals at nice locations.


Determine the tick locations for log axes.


All of these locators derive from the base class matplotlib.ticker.Locator. You can make your own locator deriving from it. Handling dates as ticks can be especially tricky. Therefore, matplotlib provides special locators in matplotlib.dates.


For quite a long time, animation in matplotlib was not an easy task and was done mainly through clever hacks. However, things have started to change since version 1.1 and the introduction of tools for creating animation very intuitively, with the possibility to save them in all kind of formats (but don't expect to be able to run very complex animations at 60 fps though).


The most easy way to make an animation in matplotlib is to declare a FuncAnimation object that specifies to matplotlib what is the figure to update, what is the update function and what is the delay between frames.

Drip drop

A very simple rain effect can be obtained by having small growing rings randomly positioned over a figure. Of course, they won't grow forever since the wave is supposed to damp with time. To simulate that, we can use a more and more transparent color as the ring is growing, up to the point where it is no more visible. At this point, we remove the ring and create a new one.

First step is to create a blank figure:

# New figure with white background
fig = plt.figure(figsize=(6,6), facecolor='white')

# New axis over the whole figure, no frame and a 1:1 aspect ratio
ax = fig.add_axes([0,0,1,1], frameon=False, aspect=1)

Next, we need to create several rings. For this, we can use the scatter plot object that is generally used to visualize points cloud, but we can also use it to draw rings by specifying we don't have a facecolor. We also have to take care of initial size and color for each ring such that we have all sizes between a minimum and a maximum size. In addition, we need to make sure the largest ring is almost transparent.

# Number of ring
n = 50
size_min = 50
size_max = 50*50

# Ring position
P = np.random.uniform(0,1,(n,2))

# Ring colors
C = np.ones((n,4)) * (0,0,0,1)
# Alpha color channel goes from 0 (transparent) to 1 (opaque)
C[:,3] = np.linspace(0,1,n)

# Ring sizes
S = np.linspace(size_min, size_max, n)

# Scatter plot
scat = ax.scatter(P[:,0], P[:,1], s=S, lw = 0.5,
                  edgecolors = C, facecolors='None')

# Ensure limits are [0,1] and remove ticks
ax.set_xlim(0,1), ax.set_xticks([])
ax.set_ylim(0,1), ax.set_yticks([])

Now, we need to write the update function for our animation. We know that at each time step each ring should grow and become more transparent while the largest ring should be totally transparent and thus removed. Of course, we won't actually remove the largest ring but re-use it to set a new ring at a new random position, with nominal size and color. Hence, we keep the number of rings constant.

def update(frame):
    global P, C, S

    # Every ring is made more transparent
    C[:,3] = np.maximum(0, C[:,3] - 1.0/n)

    # Each ring is made larger
    S += (size_max - size_min) / n

    # Reset ring specific ring (relative to frame number)
    i = frame % 50
    P[i] = np.random.uniform(0,1,2)
    S[i] = size_min
    C[i,3] = 1

    # Update scatter object

    # Return the modified object
    return scat,

Last step is to tell matplotlib to use this function as an update function for the animation and display the result or save it as a movie:

animation = FuncAnimation(fig, update, interval=10, blit=True, frames=200)
#'rain.gif', writer='imagemagick', fps=30, dpi=40)


We'll now use the rain animation to visualize earthquakes on the planet from the last 30 days. The USGS Earthquake Hazards Program is part of the National Earthquake Hazards Reduction Program (NEHRP) and provides several data on their website. Those data are sorted according to earthquakes magnitude, ranging from significant only down to all earthquakes, major or minor. You would be surprised by the number of minor earthquakes happening every hour on the planet. Since this would represent too much data for us, we'll stick to earthquakes with magnitude > 4.5. At the time of writing, this already represent more than 300 earthquakes in the last 30 days.

First step is to read and convert data. We'll use the urllib library that allows us to open and read remote data. Data on the website use the CSV format whose content is given by the first line:


We are only interested in latitude, longitude and magnitude and we won't parse time of event (ok, that's bad, feel free to send me a PR).

4.5 url = urllib.request.urlopen(feed + "4.5_month.csv") # Magnitude > 2.5 # url = urllib.request.urlopen(feed + "2.5_month.csv") # Magnitude > 1.0 # url = urllib.request.urlopen(feed + "1.0_month.csv") # Reading and storage of data data = data = data.split(b'\n')[+1:-1] E = np.zeros(len(data), dtype=[('position', float, 2), ('magnitude', float, 1)]) for i in range(len(data)): row = data[i].split(',') E['position'][i] = float(row[2]),float(row[1]) E['magnitude'][i] = float(row[4]) ">
import urllib
from mpl_toolkits.basemap import Basemap

# ->
feed = ""

# Significant earthquakes in the last 30 days
# url = urllib.request.urlopen(feed + "significant_month.csv")

# Magnitude > 4.5
url = urllib.request.urlopen(feed + "4.5_month.csv")

# Magnitude > 2.5
# url = urllib.request.urlopen(feed + "2.5_month.csv")

# Magnitude > 1.0
# url = urllib.request.urlopen(feed + "1.0_month.csv")

# Reading and storage of data
data =
data = data.split(b'\n')[+1:-1]
E = np.zeros(len(data), dtype=[('position',  float, 2),
                               ('magnitude', float, 1)])

for i in range(len(data)):
    row = data[i].split(',')
    E['position'][i] = float(row[2]),float(row[1])
    E['magnitude'][i] = float(row[4])

Now, we need to draw the earth on a figure to show precisely where the earthquake center is and to translate latitude/longitude in some coordinates matplotlib can handle. Fortunately, there is the basemap project (that tends to be replaced by the more complete cartopy) that is really simple to install and to use. First step is to define a projection to draw the earth onto a screen (there exists many different projections) and we'll stick to the mill projection which is rather standard for non-specialist like me.

fig = plt.figure(figsize=(14,10))
ax = plt.subplot(1,1,1)

earth = Basemap(projection='mill')

Next, we request to draw coastline and fill continents:

earth.drawcoastlines(color='0.50', linewidth=0.25)

The earth object will also be used to translate coordinates quite automatically. We are almost finished. Last step is to adapt the rain code and put some eye candy:

P = np.zeros(50, dtype=[('position', float, 2),
                         ('size',     float, 1),
                         ('growth',   float, 1),
                         ('color',    float, 4)])
scat = ax.scatter(P['position'][:,0], P['position'][:,1], P['size'], lw=0.5,
                  edgecolors = P['color'], facecolors='None', zorder=10)

def update(frame):
    current = frame % len(E)
    i = frame % len(P)

    P['color'][:,3] = np.maximum(0, P['color'][:,3] - 1.0/len(P))
    P['size'] += P['growth']

    magnitude = E['magnitude'][current]
    P['position'][i] = earth(*E['position'][current])
    P['size'][i] = 5
    P['growth'][i]= np.exp(magnitude) * 0.1

    if magnitude < 6:
        P['color'][i]    = 0,0,1,1
        P['color'][i]    = 1,0,0,1
    return scat,

animation = FuncAnimation(fig, update, interval=10)

If everything went well, you should obtain something like this (with animation):


Other Types of Plots

figures/plot.png figures/scatter.png figures/bar.png figures/contour.png figures/imshow.png figures/quiver.png figures/pie.png figures/grid.png figures/multiplot.png figures/polar.png figures/plot3d.png figures/text.png

Regular Plots



You need to use the fill_between command.

Starting from the code below, try to reproduce the graphic on the right taking care of filled areas.

import numpy as np
import matplotlib.pyplot as plt

n = 256
X = np.linspace(-np.pi,np.pi,n,endpoint=True)
Y = np.sin(2*X)

plt.plot (X, Y+1, color='blue', alpha=1.00)
plt.plot (X, Y-1, color='blue', alpha=1.00)

Click on figure for solution.

Scatter Plots



Color is given by angle of (X,Y).

Starting from the code below, try to reproduce the graphic on the right taking care of marker size, color and transparency.

import numpy as np
import matplotlib.pyplot as plt

n = 1024
X = np.random.normal(0,1,n)
Y = np.random.normal(0,1,n)


Click on figure for solution.

Bar Plots



You need to take care of text alignment.

Starting from the code below, try to reproduce the graphic on the right by adding labels for red bars.

import numpy as np
import matplotlib.pyplot as plt

n = 12
X = np.arange(n)
Y1 = (1-X/float(n)) * np.random.uniform(0.5,1.0,n)
Y2 = (1-X/float(n)) * np.random.uniform(0.5,1.0,n), +Y1, facecolor='#9999ff', edgecolor='white'), -Y2, facecolor='#ff9999', edgecolor='white')

for x,y in zip(X,Y1):
    plt.text(x+0.4, y+0.05, '%.2f' % y, ha='center', va= 'bottom')


Click on figure for solution.

Contour Plots



You need to use the clabel command.

Starting from the code below, try to reproduce the graphic on the right taking care of the colormap (see Colormaps below).

import numpy as np
import matplotlib.pyplot as plt

def f(x,y): return (1-x/2+x**5+y**3)*np.exp(-x**2-y**2)

n = 256
x = np.linspace(-3,3,n)
y = np.linspace(-3,3,n)
X,Y = np.meshgrid(x,y)

plt.contourf(X, Y, f(X,Y), 8, alpha=.75, cmap='jet')
C = plt.contour(X, Y, f(X,Y), 8, colors='black', linewidth=.5)

Click on figure for solution.




You need to take care of the origin of the image in the imshow command and use a colorbar.

Starting from the code below, try to reproduce the graphic on the right taking care of colormap, image interpolation and origin.

import numpy as np
import matplotlib.pyplot as plt

def f(x,y): return (1-x/2+x**5+y**3)*np.exp(-x**2-y**2)

n = 10
x = np.linspace(-3,3,4*n)
y = np.linspace(-3,3,3*n)
X,Y = np.meshgrid(x,y)

Click on figure for solution.

Pie Charts



You need to modify Z.

Starting from the code below, try to reproduce the graphic on the right taking care of colors and slices size.

import numpy as np
import matplotlib.pyplot as plt

n = 20
Z = np.random.uniform(0,1,n)

Click on figure for solution.

Quiver Plots



You need to draw arrows twice.

Starting from the code above, try to reproduce the graphic on the right taking care of colors and orientations.

import numpy as np
import matplotlib.pyplot as plt

n = 8
X,Y = np.mgrid[0:n,0:n]

Click on figure for solution.



Starting from the code below, try to reproduce the graphic on the right taking care of line styles.

import numpy as np
import matplotlib.pyplot as plt

axes = gca()

Click on figure for solution.

Multi Plots



You can use several subplots with different partition.

Starting from the code below, try to reproduce the graphic on the right.

import numpy as np
import matplotlib.pyplot as plt


Click on figure for solution.

Polar Axis



You only need to modify the axes line.

Starting from the code below, try to reproduce the graphic on the right.

import numpy as np
import matplotlib.pyplot as plt


N = 20
theta = np.arange(0.0, 2*np.pi, 2*np.pi/N)
radii = 10*np.random.rand(N)
width = np.pi/4*np.random.rand(N)
bars =, radii, width=width, bottom=0.0)

for r,bar in zip(radii, bars):
    bar.set_facecolor( cm.jet(r/10.))

Click on figure for solution.

3D Plots



You need to use contourf.

Starting from the code below, try to reproduce the graphic on the right.

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()
ax = Axes3D(fig)
X = np.arange(-4, 4, 0.25)
Y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)

ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='hot')

Click on figure for solution.




Have a look at the matplotlib logo.

Try to do the same from scratch!

Click on figure for solution.

Beyond this tutorial

Matplotlib benefits from extensive documentation as well as a large community of users and developpers. Here are some links of interest:


  • Pyplot tutorial
    • Introduction
    • Controlling line properties
    • Working with multiple figures and axes
    • Working with text
  • Image tutorial
    • Startup commands
    • Importing image data into Numpy arrays
    • Plotting numpy arrays as images
  • Text tutorial
    • Text introduction
    • Basic text commands
    • Text properties and layout
    • Writing mathematical expressions
    • Text rendering With LaTeX
    • Annotating text
  • Artist tutorial
    • Introduction
    • Customizing your objects
    • Object containers
    • Figure container
    • Axes container
    • Axis containers
    • Tick containers
  • Path tutorial
    • Introduction
    • Bézier example
    • Compound paths
  • Transforms tutorial
    • Introduction
    • Data coordinates
    • Axes coordinates
    • Blended transformations
    • Using offset transforms to create a shadow effect
    • The transformation pipeline

Matplotlib documentation

Code documentation

The code is fairly well documented and you can quickly access a specific command from within a python session:

>>> import matplotlib.pyplot as plt
>>> help(plt)
Help on function plot in module matplotlib.pyplot:

plot(*args, **kwargs)
   Plot lines and/or markers to the
   :class:`~matplotlib.axes.Axes`.  *args* is a variable length
   argument, allowing for multiple *x*, *y* pairs with an
   optional format string.  For example, each of the following is

       plot(x, y)         # plot x and y using default line style and color
       plot(x, y, 'bo')   # plot x and y using blue circle markers
       plot(y)            # plot y using x as index array 0..N-1
       plot(y, 'r+')      # ditto, but with red plusses

   If *x* and/or *y* is 2-dimensional, then the corresponding columns
   will be plotted.


The matplotlib gallery is also incredibly useful when you search how to render a given graphic. Each example comes with its source.

A smaller gallery is also available here.

Mailing lists

Finally, there is a user mailing list where you can ask for help and a developers mailing list that is more technical.

Quick references

Here is a set of tables that show main properties and styles.

Line properties

Property Description Appearance
alpha (or a) alpha transparency on 0-1 scale figures/alpha.png
antialiased True or False - use antialised rendering figures/aliased.png figures/antialiased.png
color (or c) matplotlib color arg figures/color.png
linestyle (or ls) see Line properties  
linewidth (or lw) float, the line width in points figures/linewidth.png
solid_capstyle Cap style for solid lines figures/solid_capstyle.png
solid_joinstyle Join style for solid lines figures/solid_joinstyle.png
dash_capstyle Cap style for dashes figures/dash_capstyle.png
dash_joinstyle Join style for dashes figures/dash_joinstyle.png
marker see Markers  
markeredgewidth (mew) line width around the marker symbol figures/mew.png
markeredgecolor (mec) edge color if a marker is used figures/mec.png
markerfacecolor (mfc) face color if a marker is used figures/mfc.png
markersize (ms) size of the marker in points figures/ms.png

Line styles

Symbol Description Appearance
- solid line figures/linestyle--.png
-- dashed line figures/linestyle---.png
-. dash-dot line figures/linestyle--dot.png
: dotted line figures/linestyle-:.png
. points figures/linestyle-dot.png
, pixels figures/linestyle-,.png
o circle figures/linestyle-o.png
^ triangle up figures/linestyle-^.png
v triangle down figures/linestyle-v.png
< triangle left figures/linestyle-<.png
> triangle right figures/linestyle->.png
s square figures/linestyle-s.png
+ plus figures/linestyle-+.png
x cross figures/linestyle-x.png
D diamond figures/linestyle-dd.png
d thin diamond figures/linestyle-d.png
1 tripod down figures/linestyle-1.png
2 tripod up figures/linestyle-2.png
3 tripod left figures/linestyle-3.png
4 tripod right figures/linestyle-4.png
h hexagon figures/linestyle-h.png
H rotated hexagon figures/linestyle-hh.png
p pentagon figures/linestyle-p.png
| vertical line figures/linestyle-|.png
_ horizontal line figures/linestyle-_.png


Symbol Description Appearance
0 tick left figures/marker-i0.png
1 tick right figures/marker-i1.png
2 tick up figures/marker-i2.png
3 tick down figures/marker-i3.png
4 caret left figures/marker-i4.png
5 caret right figures/marker-i5.png
6 caret up figures/marker-i6.png
7 caret down figures/marker-i7.png
o circle figures/marker-o.png
D diamond figures/marker-dd.png
h hexagon 1 figures/marker-h.png
H hexagon 2 figures/marker-hh.png
_ horizontal line figures/marker-_.png
1 tripod down figures/marker-1.png
2 tripod up figures/marker-2.png
3 tripod left figures/marker-3.png
4 tripod right figures/marker-4.png
8 octagon figures/marker-8.png
p pentagon figures/marker-p.png
^ triangle up figures/marker-^.png
v triangle down figures/marker-v.png
< triangle left figures/marker-<.png
> triangle right figures/marker->.png
d thin diamond figures/marker-d.png
, pixel figures/marker-,.png
+ plus figures/marker-+.png
. point figures/marker-dot.png
s square figures/marker-s.png
* star figures/marker-*.png
| vertical line figures/marker-|.png
x cross figures/marker-x.png
r'$\sqrt{2}$' any latex expression figures/marker-latex.png


All colormaps can be reversed by appending _r. For instance, gray_r is the reverse of gray.

If you want to know more about colormaps, see Documenting the matplotlib colormaps.


Name Appearance
autumn figures/cmap-autumn.png
bone figures/cmap-bone.png
cool figures/cmap-cool.png
copper figures/cmap-copper.png
flag figures/cmap-flag.png
gray figures/cmap-gray.png
hot figures/cmap-hot.png
hsv figures/cmap-hsv.png
jet figures/cmap-jet.png
pink figures/cmap-pink.png
prism figures/cmap-prism.png
spectral figures/cmap-spectral.png
spring figures/cmap-spring.png
summer figures/cmap-summer.png
winter figures/cmap-winter.png


Name Appearance
gist_earth figures/cmap-gist_earth.png
gist_gray figures/cmap-gist_gray.png
gist_heat figures/cmap-gist_heat.png
gist_ncar figures/cmap-gist_ncar.png
gist_rainbow figures/cmap-gist_rainbow.png
gist_stern figures/cmap-gist_stern.png
gist_yarg figures/cmap-gist_yarg.png


Name Appearance
BrBG figures/cmap-BrBG.png
PiYG figures/cmap-PiYG.png
PRGn figures/cmap-PRGn.png
PuOr figures/cmap-PuOr.png
RdBu figures/cmap-RdBu.png
RdGy figures/cmap-RdGy.png
RdYlBu figures/cmap-RdYlBu.png
RdYlGn figures/cmap-RdYlGn.png
Spectral figures/cmap-spectral-2.png


Name Appearance
Blues figures/cmap-Blues.png
BuGn figures/cmap-BuGn.png
BuPu figures/cmap-BuPu.png
GnBu figures/cmap-GnBu.png
Greens figures/cmap-Greens.png
Greys figures/cmap-Greys.png
Oranges figures/cmap-Oranges.png
OrRd figures/cmap-OrRd.png
PuBu figures/cmap-PuBu.png
PuBuGn figures/cmap-PuBuGn.png
PuRd figures/cmap-PuRd.png
Purples figures/cmap-Purples.png
RdPu figures/cmap-RdPu.png
Reds figures/cmap-Reds.png
YlGn figures/cmap-YlGn.png
YlGnBu figures/cmap-YlGnBu.png
YlOrBr figures/cmap-YlOrBr.png
YlOrRd figures/cmap-YlOrRd.png


Name Appearance
Accent figures/cmap-Accent.png
Dark2 figures/cmap-Dark2.png
Paired figures/cmap-Paired.png
Pastel1 figures/cmap-Pastel1.png
Pastel2 figures/cmap-Pastel2.png
Set1 figures/cmap-Set1.png
Set2 figures/cmap-Set2.png
Set3 figures/cmap-Set3.png


Name Appearance
afmhot figures/cmap-afmhot.png
binary figures/cmap-binary.png
brg figures/cmap-brg.png
bwr figures/cmap-bwr.png
coolwarm figures/cmap-coolwarm.png
CMRmap figures/cmap-CMRmap.png
cubehelix figures/cmap-cubehelix.png
gnuplot figures/cmap-gnuplot.png
gnuplot2 figures/cmap-gnuplot2.png
ocean figures/cmap-ocean.png
rainbow figures/cmap-rainbow.png
seismic figures/cmap-seismic.png
terrain figures/cmap-terrain.png
  • A typo in your blog

    A typo in your blog "Matplotlib tutorial"

    I understand that I should not post a typo in your blog here, but this is the only way I can contact you, since your blog points here.

    In your blog "Matplotlib tutorial", chapter "Simple Plot", section "Instantiating defaults", # savefig("../figures/exercice_2.png",dpi=72) could be changed to plt.savefig("../figures/exercice_2.png",dpi=72). You might have just missed plt in your code.

    I really appreciate your tutorial. It's the best I could find on the web.

    opened by JohnCoconut 2
  • errata on

    errata on

    Hi Nicolas, Great tutorial !

    I've used version from and there are errata in the #other-types-of-plots import maplotlib.pyplot as plt should be: import matplotlib.pyplot as plt in all examples

    in GitHub version it is just fine

    opened by LukeSkypewalker 2
  • Python plot similar to Matlab's stackedplot()

    Python plot similar to Matlab's stackedplot()

    Hello, Is there a plot function available in Python that is same as Matlab's stackedplot()? stackedplot() in Matlab can line plot several variables with the same X axis and are stacked vertically. Additionally, there is a scope in this plot that shows the value of all variables for a given X just by moving the cursor (please see the plot below). I have been able to generate subplots in Python with no issues, however, not able to add a scope like this that shows the value of all variables by moving the cursor. Is this feature available in Python?

    Thanks much for your help in advance!

    stackedplot scope2

    opened by addarnr 2
  • Divergent and sequential colormaps

    Divergent and sequential colormaps

    In the colormap section, it seems that you mistake divergent colormaps as sequential, and vice versa.

    opened by smartlixx 2
  • Update maplotlib to matlotlib

    Update maplotlib to matlotlib

    opened by cedricgilon 1
  • Typo corrections

    Typo corrections

    While reading your tutorial I noticed some minor errors. Here are the fixes.

    opened by zormit 1
  • Change drawing order

    Change drawing order

    Change zorder-attribute of the lines so that they are drawn before the tick-labels. This moves the lines to the background and the tick-labels to the foreground.

    opened by jruota 1
  • Add edges in the pie chart exercise

    Add edges in the pie chart exercise

    Edges can be specified with a dictionary of arguments passed to the wedgeprops keyword.

    opened by jruota 1
  • Minor spellcheck

    Minor spellcheck

    Hey! Thanks for writing a great, concise matplotlib tutorial. I fixed some minor spelling mistakes while reading through it, which you can merge if you like. Cheers.

    opened by tommyod 1
  • script syntax error script syntax error

    python Throws the following error:

    File "", line 19 print("Check for numpy: ", end="") ^ SyntaxError: invalid syntax

    opened by TayoO 1
  • Remove references to pylab from the tutorial?

    Remove references to pylab from the tutorial?


    I'm thinking you should maybe remove the (very) few references to pylab in your tutorial, as the offcial documentation now says "The pylab API (disapproved)"

    opened by jypeter 1
  • Drip drop animation in Jupyter notebook

    Drip drop animation in Jupyter notebook

    Hi, thanks for sharing this excellent tutorial. I am learning it via Jupyter notebook, but I found that the drip drop animation code could not update automatically. Is there any suggestion? Indeed, it works in python IDE. Thanks again.

    opened by LePingKYXK 1
  • Hiding Spines

    Hiding Spines

    Hi, thank you for your tutorial, it's been really helpful!

    In the Moving Spines section, you've used ax.spines['right'].set_color('none') to hide the axis. I wonder if ax.spines['right'].set_visible(False) would be a more elegant solution?

    opened by joel-e-m-mitchell 1
  • puzzle comment for dip

    puzzle comment for dip

    At "Instantiating defaults",

    > # Create a new figure of size 8x6 points, using 100 dots per inch
    >plt.figure(figsize=(8,6), dpi=80)

    dpi means "dots per inch", why dpi in comment is 100, in parameter is 80 ?

    opened by Sunqinying 1
  • Python v2.7 error in

    Python v2.7 error in

    We discovered in the SciPy Tutorial that the url line should be updated for people running Python V 2.7

    import urllib2 and line #26 should be changed to:

    url = urllib2.urlopen(feed + "4.5_month.csv")

    Cheers! Jen

    opened by jbosch-noaa 0
Nicolas P. Rougier
Researcher in computational and cognitive neuroscience supporting open source, open access and open science.
Nicolas P. Rougier
matplotlib: plotting with Python

Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python. Check out our home page for more inform

Matplotlib Developers 13.1k Feb 18, 2021
Handout for the tutorial "Creating publication-quality figures with matplotlib"

Handout for the tutorial "Creating publication-quality figures with matplotlib"

JB Mouret 1.7k Oct 20, 2021
Painlessly create beautiful matplotlib plots.

Announcement Thank you to everyone who has used prettyplotlib and made it what it is today! Unfortunately, I no longer have the bandwidth to maintain

Olga Botvinnik 1.6k Oct 16, 2021
:small_red_triangle: Ternary plotting library for python with matplotlib

python-ternary This is a plotting library for use with matplotlib to make ternary plots plots in the two dimensional simplex projected onto a two dime

Marc 476 Oct 23, 2021
:small_red_triangle: Ternary plotting library for python with matplotlib

python-ternary This is a plotting library for use with matplotlib to make ternary plots plots in the two dimensional simplex projected onto a two dime

Marc 391 Feb 17, 2021
Official Matplotlib cheat sheets

Official Matplotlib cheat sheets

Matplotlib Developers 5.3k Oct 18, 2021
Flexitext is a Python library that makes it easier to draw text with multiple styles in Matplotlib

Flexitext is a Python library that makes it easier to draw text with multiple styles in Matplotlib

Tomás Capretto 54 Oct 16, 2021
This package creates clean and beautiful matplotlib plots that work on light and dark backgrounds

This package creates clean and beautiful matplotlib plots that work on light and dark backgrounds. Inspired by the work of Edward Tufte.

Nico Schlömer 168 Oct 21, 2021
🧇 Make Waffle Charts in Python.

PyWaffle PyWaffle is an open source, MIT-licensed Python package for plotting waffle charts. It provides a Figure constructor class Waffle, which coul

Guangyang Li 449 Oct 23, 2021
🧇 Make Waffle Charts in Python.

PyWaffle PyWaffle is an open source, MIT-licensed Python package for plotting waffle charts. It provides a Figure constructor class Waffle, which coul

Guangyang Li 397 Feb 17, 2021
basemap - Plot on map projections (with coastlines and political boundaries) using matplotlib.

Basemap Plot on map projections (with coastlines and political boundaries) using matplotlib. ⚠️ Warning: this package is being deprecated in favour of

Matplotlib Developers 636 Oct 15, 2021
Easily convert matplotlib plots from Python into interactive Leaflet web maps.

mplleaflet mplleaflet is a Python library that converts a matplotlib plot into a webpage containing a pannable, zoomable Leaflet map. It can also embe

Jacob Wasserman 475 Sep 12, 2021
Attractors is a package for simulation and visualization of strange attractors.

attractors Attractors is a package for simulation and visualization of strange attractors. Installation The simplest way to install the module is via

Vignesh M 35 Sep 15, 2021
Python package for hypergraph analysis and visualization.

The HyperNetX library provides classes and methods for the analysis and visualization of complex network data. HyperNetX uses data structures designed to represent set systems containing nested data and/or multi-way relationships. The library generalizes traditional graph metrics to hypergraphs.

Pacific Northwest National Laboratory 164 Oct 13, 2021
A Python library for plotting hockey rinks with Matplotlib.

Hockey Rink A Python library for plotting hockey rinks with Matplotlib. Installation pip install hockey_rink Current Rinks The following shows the cus

null 6 Sep 14, 2021
Python histogram library - histograms as updateable, fully semantic objects with visualization tools. [P]ython [HYST]ograms.

physt P(i/y)thon h(i/y)stograms. Inspired (and based on) numpy.histogram, but designed for humans(TM) on steroids(TM). The goal is to unify different

Jan Pipek 115 Sep 28, 2021
649 Pokémon palettes as CSVs, with a Python lib to turn names/IDs into palettes, or MatPlotLib compatible ListedColormaps.

PokePalette 649 Pokémon, broken down into CSVs of their RGB colour palettes. Complete with a Python library to convert names or Pokédex IDs into eithe

null 9 Sep 5, 2021
HW 02 for CS40 - matplotlib practice

HW 02 for CS40 - matplotlib practice project instructions Drake Lyric Analysis Bar Char

null 2 Oct 23, 2021
Declarative statistical visualization library for Python

Altair Altair is a declarative statistical visualization library for Python. With Altair, you can spend more time understa

Altair 7k Oct 15, 2021