You are on page 1of 2

Basic plots Scales API Tick locators API Animation API

plot([X],Y,[fmt],…) API ax.set_[xy]scale(scale,…) from matplotlib import ticker import matplotlib.animation as mpla
0.0 0.0
ax.[xy]axis.set_[minor|major]_locator(locator)
Cheat sheet Version 3.5.0 X, Y, fmt, color, marker, linestyle linear log
+ any values + values > 0
2.5 2 0 2 symlog 2.510102101 0logit
- 0
ticker.NullLocator() T = np.linspace(0, 2*np.pi, 100)
S = np.sin(T)
Quick start API scatter(X,Y,…)
X, Y, [s]izes, [c]olors, marker, cmap 0.0
API
0.0
any values 0 < values < 1
ticker.MultipleLocator(0.5)
0.0 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0
line, = plt.plot(T, S)
import numpy as np
import matplotlib as mpl
2.5 1000100
-
2.5 1
+ 0 1 ticker.FixedLocator([0, 1, 5])
0 1 5
def animate(i):
line.set_ydata(np.sin(T+i/50))
import matplotlib.pyplot as plt bar[h](x,height,…) API
Projections
2 API
ticker.LinearLocator(numticks=3)
0.0 2.5 5.0
anim = mpla.FuncAnimation(
plt.gcf(), animate, interval=5)
x, height, width, bottom, align, color ticker.IndexLocator(base=0.5, offset=0.25)
0.25 0.75 1.25 1.75 2.25 2.75 3.25 3.75 4.25 4.75 plt.show()
subplot(…,projection=p)
ticker.AutoLocator()
X = np.linspace(0, 2*np.pi, 100) p=’polar’ p=’3d’ API 0 1 2 3 4 5
Y = np.cos(X) imshow(Z,…) API
ticker.MaxNLocator(n=4)
Styles API
Z, cmap, interpolation, extent, origin 0.0 1.5 3.0 4.5
fig, ax = plt.subplots() ticker.LogLocator(base=10, numticks=15) plt.style.use(style)
103 104 105 106 107 108 109 1010
ax.plot(X, Y, color=’green’) contour[f]([X],[Y],Z,…) API p=ccrs.Orthographic() API default classic grayscale
1.0
import cartopy.crs as ccrs
1.0 1.0

X, Y, Z, levels, colors, extent, origin 0.5 0.5 0.5

fig.savefig(“figure.pdf”) Tick formatters


0.0 0.0 0.0
API 0.5 0.5 0.5

fig.show() 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

pcolormesh([X],[Y],Z,…) API from matplotlib import ticker


ax.[xy]axis.set_[minor|major]_formatter(formatter)
ggplot seaborn fast
Anatomy of a figure X, Y, Z, vmin, vmax, cmap
1.0 1.0 1.0

Lines
0.5 0.5 0.5
API
ticker.NullFormatter()
0.0 0.0 0.0

0.5 0.5 0.5

4
Anatomy of a figure linestyle or ls
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

Title Blue signal


quiver([X],[Y],U,V,…) API ticker.FixedFormatter(['zero', 'one', 'two', ]) bmh Solarize_Light2 seaborn-notebook
Major tick Red signal X, Y, U, V, C, units, angles zero one two three four five 1.0 1.0 1.0
"-" ":" "--" "-." (0,(0.01,2)) 0.5 0.5 0.5

Legend ticker.FuncFormatter(lambda x, pos: "[%.2f]" % x)


capstyle or dash_capstyle 0.0 0.0 0.0

0.5 0.5 0.5


[0.00] [1.00] [2.00] [3.00] [4.00] [5.00]
Minor tick 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

pie(X,…) API "butt" "round" "projecting" ticker.FormatStrFormatter('>%d<')


3
Major tick label Grid
Z, explode, labels, colors, radius >0< >1< >2< >3< >4< >5<

Line
ticker.ScalarFormatter() Quick reminder
(line plot) Markers API 0 1 2 3 4 5

text(x,y,text,…) API ticker.StrMethodFormatter('{x}') ax.grid()


T
Y axis label

TEX
2 x, y, text, va, ha, size, weight, transform 0.0 1.0 2.0 3.0 4.0 5.0 ax.set_[xy]lim(vmin, vmax)
'.' 'o' 's' 'P' 'X' '*' 'p' 'D' '<' '>' '^' 'v' ticker.PercentFormatter(xmax=5) ax.set_[xy]label(label)
Y axis label 0% 20% 40% 60% 80% 100%
Markers ax.set_[xy]ticks(ticks, [labels])
(scatter plot)
fill[_between][x](…) API '1' '2' '3' '4' '+' 'x' '|' '_' 4 5 6 7 ax.set_[xy]ticklabels(labels)
1
X, Y1, Y2, color, where Ornaments ax.set_title(title)
'$ $''$ $''$ $''$ $''$ $''$ $''$ $''$ $''$ $''$ $''$ $''$ $' ax.tick_params(width=10, …)
Spines
markevery ax.legend(…) API ax.set_axis_[on|off]()
Figure Line
10 [0, -1] (25, 5) [0, 25, -1] handles, labels, loc, title, frameon
Axes (line plot)
Advanced plots fig.suptitle(title)
0 title
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
Minor tick label
X axis label step(X,Y,[fmt],…) API
Colors API
Legend label
fig.tight_layout()
plt.gcf(), plt.gca()
X axis label X, Y, fmt, color, marker, where handletextpad handle
markerfacecolor (mfc)
1 C0 C1 C2 C3 C4 C5 C6 C7 C8 C9
handlelength mpl.rc(’axes’, linewidth=1, …)
0
’Cn’ Label 1 Label 3 [fig|ax].patch.set_alpha(0)
Subplots layout API 0 b 2 g 4 r 6 c 8 m 10 y 12 k 14 w 16 ’x’
1 DarkRed Firebrick Crimson IndianRed Salmon labelspacing markeredgecolor (mec) text=r’$\frac{-e^{i\pi}}{2^n}$’
boxplot(X,…) API
X, notch, sym, bootstrap, widths 10 (1,0,0) (1,0,0,0.75) (1,0,0,0.5) (1,0,0,0.25)
’name’ Label 2 Label 4
subplot[s](rows,cols,…) API 0 2 4 6 8 10 12 14 16 (R,G,B[,A])
10 #FF0000 borderpad columnspacing numpoints or scatterpoints
fig, axs = plt.subplots(3, 3) 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 borderaxespad
Keyboard shortcuts API
0 2 4 6 8 10 12 14 16 ’x.y’
0
errorbar(X,Y,xerr,yerr,…) API 0 2 4 6 8 10 12 14 16 ctrl + s Save ctrl + w Close plot
G = gridspec(rows,cols,…) API X, Y, xerr, yerr, fmt ax.colorbar(…) API
ax = G[0,:] Colormaps API mappable, ax, cax, orientation r Reset view f Fullscreen 0/1
f View forward b View back
hist(X, bins, …) API plt.get_cmap(name) p Pan view o Zoom to rect
ax.inset_axes(extent) API X, bins, range, density, weights 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0
Uniform x X pan/zoom y Y pan/zoom
viridis g Minor grid 0/1 G Major grid 0/1
violinplot(D,…) API magma
ax.annotate(…) API l X axis log/linear L Y axis log/linear
d=make_axes_locatable(ax) API D, positions, widths, vert plasma
text, xy, xytext, xycoords, textcoords, arrowprops
ax = d.new_horizontal(’10%’) Sequential
barbs([X],[Y], U, V, …) API
Greys
text Ten simple rules READ
YlOrBr xytext xy
X, Y, U, V, C, length, pivot, sizes textcoords xycoords
Wistia 1. Know your audience
Getting help Diverging 2. Identify your message
Spectral 3. Adapt the figure
matplotlib.org eventplot(positions,…) API
4. Captions are not optional
Å
positions, orientation, lineoffsets
coolwarm
Event handling API
H github.com/matplotlib/matplotlib/issues RdGy 5. Do not trust the defaults
ď discourse.matplotlib.org Qualitative fig, ax = plt.subplots() 6. Use color effectively
W stackoverflow.com/questions/tagged/matplotlib hexbin(X,Y,C,…) API
tab10 def on_click(event): 7. Do not mislead the reader
Ż https://gitter.im/matplotlib/matplotlib X, Y, C, gridsize, bins
tab20 print(event) 8. Avoid “chartjunk”
F twitter.com/matplotlib Cyclic fig.canvas.mpl_connect( 9. Message trumps beauty
a Matplotlib users mailing list twilight ’button_press_event’, on_click) 10. Get the right tool
Axes adjustments API Uniform colormaps Color names API Legend placement How do I …
plt.subplots_adjust( … ) viridis
plasma
black
k
dimgray
dimgrey
floralwhite
darkgoldenrod
goldenrod
cornsilk
darkturquoise
cadetblue
powderblue
lightblue
L K J … resize a figure?
→ fig.set_size_inches(w, h)
… save a figure?
gray gold deepskyblue

A 2 9 1 I
grey lemonchiffon skyblue
inferno
darkgray khaki lightskyblue → fig.savefig(”figure.pdf”)
magma darkgrey palegoldenrod steelblue … save a transparent figure?
silver darkkhaki aliceblue
top cividis lightgray ivory dodgerblue → fig.savefig(”figure.pdf”, transparent=True)
axes width lightgrey beige lightslategray
gainsboro lightyellow lightslategrey … clear a figure/an axes?
whitesmoke lightgoldenrodyellow slategray
w olive slategrey → fig.clear() → ax.clear()
Sequential colormaps white y lightsteelblue
snow yellow cornflowerblue … close all figures?
B 6 10 7 H
rosybrown olivedrab royalblue

figure height
axes height
lightcoral
indianred
yellowgreen
darkolivegreen
ghostwhite
lavender → plt.close(”all”)
Greys brown
firebrick
greenyellow
chartreuse
midnightblue
navy … remove ticks?
hspace Purples maroon
darkred
lawngreen
honeydew
darkblue
mediumblue
→ ax.set_[xy]ticks([])
Blues r
red
darkseagreen
palegreen
b
blue
… remove tick labels ?
Greens mistyrose lightgreen slateblue → ax.set_[xy]ticklabels([])
salmon forestgreen darkslateblue
… rotate tick labels ?
C 3 8 4 G
left bottom wspace right Oranges tomato limegreen mediumslateblue
darksalmon darkgreen mediumpurple
Reds coral g rebeccapurple → ax.tick_params(axis=”x”, rotation=90)
orangered green blueviolet
YlOrBr lightsalmon lime indigo … hide top spine?
figure width sienna seagreen darkorchid
YlOrRd
OrRd
seashell
chocolate
saddlebrown
sandybrown
mediumseagreen
springgreen
mintcream
mediumspringgreen
darkviolet
mediumorchid
thistle
plum
D E F → ax.spines[’top’].set_visible(False)
… hide legend border?
→ ax.legend(frameon=False)
PuRd peachpuff mediumaquamarine violet
Extent & origin API
RdPu
peru
linen
aquamarine
turquoise
purple
darkmagenta
ax.legend(loc=”string”, bbox_to_anchor=(x,y)) … show error as shaded region?
bisque lightseagreen m → ax.fill_between(X, Y+error, Y‐error)
ax.imshow( extent=…, origin=… ) BuPu darkorange mediumturquoise fuchsia 2: upper left 9: upper center 1: upper right
burlywood azure magenta … draw a rectangle?
GnBu antiquewhite lightcyan orchid 6: center left 10: center 7: center right
tan paleturquoise mediumvioletred → ax.add_patch(plt.Rectangle((0, 0), 1, 1)
5
origin="upper" origin="upper" PuBu navajowhite darkslategray deeppink 3: lower left 8: lower center 4: lower right
(0,0) (0,0) blanchedalmond darkslategrey hotpink … draw a vertical line?
YlGnBu papayawhip teal lavenderblush
PuBuGn
moccasin
orange
darkcyan
c
palevioletred
crimson
A: upper right / (-0.1,0.9) B: center right / (-0.1,0.5) → ax.axvline(x=0.5)
BuGn
wheat
oldlace
aqua
cyan
pink
lightpink
C: lower right / (-0.1,0.1) D: upper left / (0.1,-0.1) … draw outside frame?
0
(4,4) (4,4) E: upper center / (0.5,-0.1) F: upper right / (0.9,-0.1) → ax.plot(…, clip_on=False)
YlGn
extent=[0,10,0,5] extent=[10,0,0,5] G: lower left / (1.1,0.1) H: center left / (1.1,0.5) … use transparency?
I: upper left / (1.1,0.9) J: lower right / (0.9,1.1) → ax.plot(…, alpha=0.25)
origin="lower" origin="lower" Image interpolation API
5
(4,4) (4,4) Diverging colormaps K: lower center / (0.5,1.1) L: lower left / (0.1,1.1) … convert an RGB image into a gray image?
→ gray = 0.2989*R + 0.5870*G + 0.1140*B
PiYG … set figure background color?
0
(0,0) (0,0) PRGn Annotation connection styles API → fig.patch.set_facecolor(“grey”)
extent=[0,10,0,5] extent=[10,0,0,5]
BrBG
… get a reversed colormap?
0 10 0 10
arc3, arc3, angle3, → plt.get_cmap(“viridis_r”)
PuOr rad=0 rad=0.3 angleA=0,
angleB=90 … get a discrete colormap?
RdGy None none nearest
Text alignments API → plt.get_cmap(“viridis”, 10)
RdBu
… show a figure for one second?
ax.text( …, ha=… , va=…, …) RdYlBu
→ fig.show(block=False), time.sleep(1)

Matplotlib
RdYlGn
(1,1)
Performance tips
Spectral
top
angle, angle, arc,
coolwarm angleA=-90,
angleA=-90, angleA=-90,
center bwr angleB=180, angleB=180, angleB=0,
bilinear bicubic spline16 rad=0 rad=10 armA=0, scatter(X, Y) slow
baseline seismic armB=20,
bottom rad=0 plot(X, Y, marker=”o”, ls=””) fast
(0,0)
left center right for i in range(n): plot(X[i]) slow
Qualitative colormaps plot(sum([x+[None] for x in X],[])) fast

Text parameters API bar, bar, bar,


cla(), imshow(…), canvas.draw() slow
Pastel1 fraction=0.3 fraction=-0.3 angle=180, im.set_data(…), canvas.draw() fast
ax.text(…, family=…, size=…, weight=…) Pastel2 spline36 hanning hamming
fraction=-0.2

ax.text(…, fontproperties=…) Paired Beyond Matplotlib


The quick brown fox
Accent
xx-large (1.73)
Dark2 Seaborn: Statistical data visualization
The quick brown fox x-large (1.44)
Set1 Cartopy: Geospatial data processing
The quick brown fox large (1.20)
Set2 yt: Volumetric data visualization
The quick brown fox medium (1.00)
The quick brown fox mpld3: Bringing Matplotlib to the browser
The quick brown fox
small
x-small
(0.83)
(0.69)
Set3 hermite kaiser quadric Annotation arrow styles API
Datashader: Large data processing pipeline
The quick brown fox xx-small (0.58) tab10
tab20 plotnine: A grammar of graphics for Python
The quick brown fox jumps over the lazy dog black (900)
- <- -> <->
The quick brown fox jumps over the lazy dog bold (700) tab20b
The quick brown fox jumps over the lazy dog semibold (600) tab20c
The quick brown fox jumps over the lazy dog normal (400) Matplotlib Cheatsheets
The quick brown fox jumps over the lazy dog ultralight (100)
<|- -|> <|-|> ]- Copyright (c) 2021 Matplotlib Development Team
The quick brown fox jumps over the lazy dog monospace Miscellaneous colormaps catrom gaussian bessel Released under a CC‐BY 4.0 International License
The quick brown fox jumps over the lazy dog serif
The quick brown fox jumps over the lazy dog sans
The quick brown fox jumps over the lazy dog cursive
terrain -[ ]-[ |-| ]->
ocean
The quick brown fox jumps over the lazy dog italic
The quick brown fox jumps over the lazy dog normal cubehelix

The quick brown fox jumps over the lazy dog small-caps
rainbow <-[ simple fancy wedge
The quick brown fox jumps over the lazy dog normal twilight mitchell sinc lanczos

You might also like