You are on page 1of 3

Basic plots Scales API Tick locators API Animation API

P. ROUGIER
756

DESIGNED BY NICOLAS
plot([X],Y,[fmt],…) API ax.set_[xy]scale(scale,…) from matplotlib import ticker import matplotlib.animation as mpla
Cheat sheet
432 Version 3.2 X, Y, fmt, color, marker, linestyle
0.0 linear
0.0 log
ax.[xy]axis.set_[minor|major]_locator(locator)

1 2.5- + any values 0 + values > 0


2.510102101 0logit
ticker.NullLocator() T = np.linspace(0,2*np.pi,100)

Quick start 765 1234567 X,scatter(X,Y,…) API


0.0 2 0 2 symlog
0.0 ticker.MultipleLocator(0.5)
S = np.sin(T)
line, = plt.plot(T, S)
423
API
0.0 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0
Y, [s]izes, [c]olors, marker, cmap any values 0 < values < 1
import numpy as np
1 2.5 1000100
- +
2.5 1 0 1
0
ticker.FixedLocator([0, 1, 5])
1 5
def animate(i):
line.set_ydata(np.sin(T+i/50))

6754 1234567 x,bar[h](x,height,…)


import matplotlib as mpl ticker.LinearLocator(numticks=3)
import matplotlib.pyplot as plt API
Projections
2 API
0.0 2.5 5.0
anim = mpla.FuncAnimation(
plt.gcf(), animate, interval=5)
ticker.IndexLocator(base=0.5, offset=0.25)
height, width, bottom, align, color
321 subplot(…,projection=p)
0.25 0.75
ticker.AutoLocator()
1.25 1.75 2.25 2.75 3.25 3.75 4.25 4.75 plt.show()

765 1234567 imshow(Z,[cmap],…)


X = np.linspace(0, 2*np.pi, 100) 0 1 2 3 4 5
p=’polar’ p=’3d’
API ticker.MaxNLocator(n=4) Styles
3421
Y = np.cos(X) API
Z, cmap, interpolation, extent, origin 0.0 1.5 3.0 4.5
ticker.LogLocator(base=10, numticks=15)
fig, ax = plt.subplots() 103 104 105 106 107 108 109 1010 plt.style.use(style)

6754 1234567 contour[f]([X],[Y],Z„…)


ax.plot(X,Y,color=’C1’) API p=Orthographic() API default classic grayscale
1.0
from cartopy.crs import Cartographic
1.0 1.0

X, Y, Z, levels, colors, extent, origin Tick formatters


321
0.5 0.5 0.5
API
fig.savefig(“figure.pdf”) 0.0

0.5
0.0
0.5
0.0

0.5

fig.show()
765 1234567 quiver([X],[Y],U,V,…)
from matplotlib import ticker 1.0
0 1 2 3 4 5 6
1.0
0 1 2 3 4 5 6 7
1.0
0 1 2 3 4 5 6

ax.[xy]axis.set_[minor|major]_formatter(formatter)
API ggplot seaborn fast

3421 X, Y, U, V, C, units, angles


1.0 1.0 1.0

Anatomy of a figure Lines


0.5 0.5
ticker.NullFormatter()
0.5

API 0.0 0.0 0.0

0.5 0.5 0.5

765 1234567 pie(X,[explode],…)


1.0 1.0

linestyle or ls ticker.FixedFormatter(['', '0', '1', ...])


1.0
0 1 2 3 4 5 6 0 1 2 3 4 5 6 0 1 2 3 4 5 6

API 0 0.25 0.50 1 0.75 0.25 2 0.50 0.75 3 0.25 0.50 0.75 4 0.25 0.50 5
bmh Solarize_Light2 seaborn-notebook
Anatomy of a figure
4 432 Z, explode, labels, colors, radius "-" ":" "--" "-." (0,(0.01,2)) ticker.FuncFormatter(lambda x, pos: "[%.2f]" % x)
1.0

0.5
1.0

0.5
1.0
0.5

1
Title
Major tick
Blue signal
Red signal capstyle or dash_capstyle [0.00] [1.00] [2.00] [3.00] [4.00] [5.00] 0.0

0.5
0.0

0.5
0.0
0.5

765 1234567T x, y, text, va, ha, size, weight, transform


Legend ticker.FormatStrFormatter('>%d<') 1.0
0 1 2 3 4 5 6
1.0
0 1 2 3 4 5 6
1.0
0 1 2 3 4 5 6

text(x,y,text,…) API "butt" "round" "projecting" >0< >1< >2< >3< >4< >5<

432 TEX
Minor tick
ticker.ScalarFormatter()
3
Quick reminder
1
0 1 2 3 4 5
Major tick label Grid
Markers ticker.StrMethodFormatter('{x}')

765 1234567 X,fill[_between][x](


Line API
(line plot) 0.0 1.0 2.0 3.0 4.0 5.0 ax.grid()
… ) API

432 Y1, Y2, color, where ticker.PercentFormatter(xmax=5) ax.patch.set_alpha(0)


Y axis label

2 0% 20% 40% 60% 80% 100%

1 '.' 'o' 's' 'P' 'X' '*' 'p' 'D' '<' '>' '^' 'v' ax.set_[xy]lim(vmin, vmax)
ax.set_[xy]label(label)
1234567
Y axis label Markers
Ornaments
(scatter plot)
'1' '2' '3' '4' '+' 'x' '|' '_' 4 5 6 7 ax.set_[xy]ticks(list)
1 Advanced plots ax.set_[xy]ticklabels(list)
ax.legend(…)
765
'$ $''$ $''$ $''$ $''$ $''$ $''$ $''$ $''$ $''$ $''$ $''$ $' API ax.set_[sup]title(title)
Spines step(X,Y,[fmt],…) API markevery handles, labels, loc, title, frameon ax.tick_params(width=10, …)
Figure
Axes
Line
(line plot)
432 X, Y, fmt, color, marker, where 10 [0, -1] (25, 5) [0, 25, -1] ax.set_axis_[on|off]()
1
title
0
0 0.25 0.50 0.75 1 1.25 1.50 1.75 2 2.25 2.50 2.75 3 3.25 3.50 3.75 4 Legend
765 1234567 X,boxplot(X,…)
label
Minor tick label
X axis label handletextpad handle
markerfacecolor (mfc)
ax.tight_layout()
X axis label API
Colors
432
handlelength
API plt.gcf(), plt.gca()
notch, sym, bootstrap, widths Label 1 Label 3 mpl.rc(’axes’, linewidth=1, …)
1
1 C0 C1 C2 C3 C4 C5 C6 C7 C8 C9 labelspacing markeredgecolor (mec)
Subplots layout
’Cn’ fig.patch.set_alpha(0)
0
Label 2 Label 4
765 246 X,errorbar(X,Y,xerr,yerr,…)
API
0 b 2 g 4 r 6 c 8 m 10 y 12 k 14 w 16 ’x’ text=r’$\frac{-e^{i\pi}}{2^n}$’
API 1 DarkRed Firebrick Crimson IndianRed Salmon borderpad

fig, axs = plt.subplots(3,3) 4


’name’ columnspacing numpoints or scatterpoints

Y, xerr, yerr, fmt 10 (1,0,0) (1,0,0,0.75) (1,0,0,0.5) (1,0,0,0.25)


312
subplot[s](rows,cols,…) API
0 2 4 6 8 10 12 14 16 (R,G,B[,A])
10 #FF0000 borderaxespad
0 2 4 #FF0000BB
6 8 #FF000088
10 12 #FF000044
14 16 ’#RRGGBB[AA]’
10 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 Keyboard shortcuts API

71
61
51 1234567 X,hist(X, bins, …) API
0
0
0
2
2
4
4
6
6
8
8
10 12 14 16 ’x.y’
10 12 14 16 ax.colorbar(…) API
ctrl + s Save ctrl + w Close plot
G = gridspec(rows,cols,…)
41
31
21
API bins, range, density, weights mappable, ax, cax, orientation
Reset view Fullscreen 0/1
111 Colormaps
ax = G[0,:] r f
API
View forward b View back
765 1234567 violinplot(D,…)
f
API plt.get_cmap(name) 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0
Pan view o Zoom to rect
423
p
ax.inset_axes(extent) API D, positions, widths, vert
Uniform X pan/zoom y Y pan/zoom
1
x
viridis ax.annotate(…) Minor grid 0/1 G Major grid 0/1
756 1234567 barbs([X],[Y],
API g
U, V, …) API magma text, xy, xytext, xycoords, textcoords, arrowprops
X axis log/linear L Y axis log/linear
4
l
X, Y, U, V, C, length, pivot, sizes
321
d=make_axes_locatable(ax) API plasma
ax=d.new_horizontal(’10%’) Sequential Annotation
Ten simple rules
765 1234567 eventplot(positions,…) xytext xy
Greys READ
API YlOrBr textcoords ycoords

423 positions, orientation, lineoffsets Wistia 1. Know Your Audience


Getting help 1 Diverging 2. Identify Your Message

6754 1234567 X, Y, C, gridsize, bins


Spectral 3. Adapt the Figure
matplotlib.org hexbin(X,Y,C,…) API
4. Captions Are Not Optional
coolwarm
Event handling
321
API
github.com/matplotlib/matplotlib/issues RdGy 5. Do Not Trust the Defaults
discourse.matplotlib.org Qualitative 6. Use Color Effectively
0.2500
fig, ax = plt.subplots()
0.1875
stackoverflow.com/questions/tagged/matplotlib
0.1250
0.0625 1234567 xcorr(X,Y,…) API
tab10 def on_click(event): 7. Do Not Mislead the Reader
gitter.im/matplotlib
0.0000 8. Avoid “Chartjunk”
tab20 print(event)
X, Y, normed, detrend
twitter.com/matplotlib 0.0625
0.1250
0.1875 Cyclic fig.canvas.mpl_connect( 9. Message Trumps Beauty
Matplotlib users mailing list
0.2500 86420246 twilight ’button_press_event’, on_click) 10. Get the Right Tool
Axes adjustments API Uniform colormaps Color names API Legend placement Annotation arrow styles API

plt.subplot_adjust( … )
L K J
black floralwhite darkturquoise
viridis k darkgoldenrod cadetblue
dimgray goldenrod powderblue
plasma dimgrey cornsilk lightblue
gray gold deepskyblue - <- ->
grey lemonchiffon skyblue

A 7 8 9 I
inferno darkgray khaki lightskyblue
magma darkgrey palegoldenrod steelblue
silver darkkhaki aliceblue
lightgray ivory dodgerblue <-> <|- -|>
top axes width
cividis lightgrey beige lightslategray
gainsboro lightyellow lightslategrey
whitesmoke lightgoldenrodyellow slategray
w olive slategrey <|-|> ]-[ ]-
white y lightsteelblue
Sequential colormaps snow
rosybrown
yellow
olivedrab
cornflowerblue
royalblue
lightcoral yellowgreen ghostwhite
B 4 5 6 H

figure height
indianred darkolivegreen lavender -[ |-| simple
axes height brown greenyellow midnightblue
Greys firebrick chartreuse navy
maroon lawngreen darkblue
hspace Purples darkred honeydew mediumblue fancy wedge
r darkseagreen b
Blues red palegreen blue
mistyrose lightgreen slateblue
Greens salmon forestgreen darkslateblue
tomato limegreen mediumslateblue
darksalmon darkgreen mediumpurple
bottom coral g rebeccapurple
C 1 2 3 G
left wspace right Oranges
orangered green blueviolet
Reds lightsalmon lime indigo
YlOrBr
sienna
seashell
seagreen
mediumseagreen
darkorchid
darkviolet
How do I …
chocolate springgreen mediumorchid
D E F
figure width
YlOrRd saddlebrown
sandybrown
mintcream
mediumspringgreen
thistle
plum … resize a figure?
OrRd peachpuff
peru
mediumaquamarine
aquamarine
violet
purple → fig.set_size_inches(w,h)
linen turquoise darkmagenta … save a figure?
Extent & origin API
PuRd bisque
darkorange
lightseagreen
mediumturquoise
m
fuchsia ax.legend(loc=”string”, bbox_to_anchor=(x,y))
RdPu burlywood azure magenta → fig.savefig(”figure.pdf”)
antiquewhite lightcyan orchid
ax.imshow( extent=…, origin=… ) BuPu tan paleturquoise mediumvioletred 1: lower left 2: lower center 3: lower right … save a transparent figure?
navajowhite darkslategray deeppink
GnBu blanchedalmond darkslategrey hotpink 4: center left 5: center 6: center right → fig.savefig(”figure.pdf”, transparent=True)
papayawhip teal lavenderblush
origin="upper" origin="upper" PuBu
moccasin
orange
darkcyan
c
palevioletred
crimson 7: upper left 8: upper center 9: upper right … clear a figure?
5
(0,0) (0,0) wheat
oldlace
aqua
cyan
pink
lightpink
→ ax.clear()
YlGnBu
A: upper right / B: center right / … close all figures?
PuBuGn
(-.1,.9) (-.1,.5) → plt.close(”all”)
(4,4) (4,4)
BuGn C: lower right / D: upper left / (.1,-.1) … remove ticks?
0 YlGn
extent=[0,10,0,5] extent=[10,0,0,5] (-.1,.1) → ax.set_xticks([])
origin="lower" origin="lower" E: upper center / F: upper right / … remove tick labels ?
5
(4,4) (4,4) Image interpolation
Diverging colormaps (.5,-.1) (.9,-.1) → ax.set_[xy]ticklabels([])
API
G: lower left / (1.1,.1) H: center left / … rotate tick labels ?
(1.1,.5) → ax.set_[xy]ticks(rotation=90)
PiYG
0
(0,0) (0,0) I: upper left / (1.1,.9) J: lower right / … hide top spine?
extent=[0,10,0,5] extent=[10,0,0,5] PRGn
0 10 0 10 (.9,1.1) → ax.spines[’top’].set_visible(False)
BrBG
K: lower center / L: lower left / (.1,1.1) … hide legend border?
PuOr (.5,1.1) → ax.legend(frameon=False)
Text alignments API RdGy None none nearest … show error as shaded region?
RdBu
ax.text( …, ha=… , va=…, … ) → ax.fill_between(X, Y+error, Y‐error)
RdYlBu
… draw a rectangle?
→ ax.add_patch(plt.Rectangle((0, 0),1,1)

Matplotlib
RdYlGn

(1,1)
Spectral
… draw a vertical line?
top coolwarm → ax.axvline(x=0.5)
center bwr bilinear bicubic spline16 Annotation connection styles API
… draw outside frame?
baseline seismic → ax.plot(…, clip_on=False)
bottom
(0,0) … use transparency?
left center right arc3, arc3, angle3,
rad=0 rad=0.3 angleA=0,
→ ax.plot(…, alpha=0.25)
Qualitative colormaps angleB=90

… convert an RGB image into a gray image?


Text parameters API
→ gray = 0.2989*R+0.5870*G+0.1140*B
Pastel1
spline36 hanning hamming … set figure background color?
ax.text( …, family=… , size=…, weight = …)
Pastel2
→ fig.patch.set_facecolor(“grey”)
ax.text( …, fontproperties = … )
Paired … get a reversed colormap?
Accent angle,
angleA=-90,
angle,
angleA=-90,
arc,
angleA=-90, → plt.get_cmap(“viridis_r”)
… get a discrete colormap?
angleB=180, angleB=180, angleB=0,

The quick brown fox xx-large (1.73)


Dark2 rad=0 rad=25 armA=0,
armB=40,

The quick brown fox x-large (1.44)


Set1 rad=0
→ plt.get_cmap(“viridis”, 10)
The quick brown fox Set2 … show a figure for one second?
The quick brown fox
large
medium
(1.20)
(1.00) Set3
hermite kaiser quadric → fig.show(block=False), time.sleep(1)
The quick brown fox small (0.83)
The quick brown fox x-small (0.69) tab10
The quick brown fox xx-small (0.58)
tab20 bar, bar, bar,
fraction=0.3 fraction=-0.3 angle=180,
The quick brown fox jumps over the lazy dog black (900) tab20b fraction=-0.2

The quick brown fox jumps over the lazy dog


The quick brown fox jumps over the lazy dog
bold
semibold
(700)
(600) tab20c Performance tips
The quick brown fox jumps over the lazy dog normal (400)
The quick brown fox jumps over the lazy dog ultralight (100) catrom gaussian bessel scatter(X, Y) slow
The quick brown fox jumps over the lazy dog monospace Miscellaneous colormaps plot(X, Y, marker=”o”, ls=””) fast
The quick brown fox jumps over the lazy dog serif
The quick brown fox jumps over the lazy dog sans
for i in range(n): plot(X[i]) slow
The quick brown fox jumps over the lazy dog cursive
terrain plot(sum([x+[None] for x in X],[])) fast
ocean
The quick brown fox jumps over the lazy dog italic cla(), imshow(…), canvas.draw() slow
The quick brown fox jumps over the lazy dog normal cubehelix im.set_data(…), canvas.draw() fast
The quick brown fox jumps over the lazy dog small-caps
rainbow mitchell sinc lanczos
The quick brown fox jumps over the lazy dog normal twilight
Beyond Matplotlib

Seaborn: Statistical Data Visualization


Cartopy: Geospatial Data Processing
yt: Volumetric data Visualization
mpld3: Bringing Matplotlib to the browser
Datashader: Large data processing pipeline
plotnine: A Grammar of Graphics for Python

Matplotlib Cheatsheets (c) 2020 Nicolas P. Rougier


Released under a CC‐BY 4.0 International License

You might also like