You are on page 1of 2

Basic plots Scales API Tick locators API Animation API

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

1 - + any values
2.5 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 API


0.0 2 0 2 symlog 0.0 ticker.MultipleLocator(0.5)
S = np.sin(T)
line, = plt.plot(T, S)
423 Y, [s]izes, [c]olors, marker, cmap
-
2.5 1000100any values2.5 1 0 < values < 1
+ 0 1
0.0 0.5 1.0
ticker.FixedLocator([0, 1, 5])
1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0
def animate(i):
import numpy as np
1 2
0 1 5 line.set_ydata(np.sin(T+i/50))
756 1234567 x,bar[h](x,height,…)
import matplotlib as mpl ticker.LinearLocator(numticks=3) anim = mpla.FuncAnimation(
import matplotlib.pyplot as plt API Projections API 0.0 2.5 5.0

432
plt.gcf(), animate, interval=5)
height, width, bottom, align, color ticker.IndexLocator(base=0.5, offset=0.25)
plt.show()
1 subplot(…,projection=p) 0.25 0.75 1.25 1.75 2.25 2.75 3.25 3.75 4.25 4.75
ticker.AutoLocator()
X = np.linspace(0, 2*np.pi, 100)
765 1234567 imshow(Z,…) API
p=’polar’ p=’3d’ 0 1 2 3 4 5
Styles API

3421
Y = np.cos(X) ticker.MaxNLocator(n=4)
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)

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


103 104 105 106 107 108 109 1010
ax.plot(X, Y, color=’green’) p=Orthographic() API
default grayscale
API classic
from cartopy.crs import Cartographic 1.0 1.0 1.0

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


3
0.5

21
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()
32 1234567 pcolormesh([X],[Y],Z,…)
1.0 1.0 1.0
0 1 2 3 4 5 6 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6

10 API ggplot seaborn fast


from matplotlib import ticker

Anatomy of a figure X, Y, Z, vmin, vmax, cmap


1.0 1.0 1.0
ax.[xy]axis.set_[minor|major]_formatter(formatter)

12 Lines 0.5 0.5


API
0.5

0.0 0.0 0.0

7653 3210123 quiver([X],[Y],U,V,…)


ticker.NullFormatter() 0.5 0.5 0.5

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

API ticker.FixedFormatter(['zero', 'one', 'two', ]) bmh Solarize_Light2 seaborn-notebook


432
Title Blue signal
Major tick X, Y, U, V, C, units, angles
1.0 1.0 1.0
Red signal "-" ":" "--" "-." (0,(0.01,2)) zero one two three four five 0.5 0.5 0.5

1 capstyle or dash_capstyle
Legend ticker.FuncFormatter(lambda x, pos: "[%.2f]" % x) 0.0 0.0 0.0

0.5 0.5 0.5

765 1234567 Z, explode, labels, colors, radius


Minor tick [0.00] [1.00] [2.00] [3.00] [4.00] [5.00] 1.0 1.0 1.0

"butt" "round" "projecting"


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

pie(X,…) API ticker.FormatStrFormatter('>%d<')

432
3
>0< >1< >2< >3< >4< >5<
Major tick label Grid
Quick reminder
Line
(line plot) 1 Markers API 0
ticker.ScalarFormatter()
1 2 3 4 5

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


Y axis label

2
432 TEX 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)

1 ax.set_[xy]label(label)
'.' 'o' 's' 'P' 'X' '*' 'p' 'D' '<' '>' '^' 'v' ticker.PercentFormatter(xmax=5)
Y axis label 0% 20% 40% 60% 80% 100% ax.set_[xy]ticks(ticks, [labels])
756 1234567 X,fill[_between][x](…)
Markers
(scatter plot)
API '1' '2' '3' '4' '+' 'x' '|' '_' 4 5 6 7 ax.set_[xy]ticklabels(labels)
1 432 Y1, Y2, color, where
Ornaments
ax.set_title(title)
1 '$ $''$ $''$ $''$ $''$ $''$ $''$ $''$ $''$ $''$ $''$ $''$ $'
markevery
ax.tick_params(width=10, …)

1234567
Spines 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

765
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 fig.tight_layout()
X axis label step(X,Y,[fmt],…) API
Colors Legend
432
Minor tick label API plt.gcf(), plt.gca()
X axis label X, Y, fmt, color, marker, where handletextpad
label
handle
1 C0 C1 C2 C3 C4 C5 C6 C7 C8 C9 markerfacecolor (mfc) mpl.rc(’axes’, linewidth=1, …)
1
handlelength
’Cn’
Subplots layout
0 Label 1 Label 3 [fig|ax].patch.set_alpha(0)
765 1234567 X,boxplot(X,…)
API 0 b 2 g 4 r 6 c 8 m 10 y 12 k 14 w 16 ’x’
API 1 DarkRed Firebrick Crimson IndianRed Salmon labelspacing markeredgecolor (mec) text=r’$\frac{-e^{i\pi}}{2^n}$’
’name’

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


subplot[s](rows,cols,…) API
42 10 (1,0,0) (1,0,0,0.75) (1,0,0,0.5) (1,0,0,0.25)
notch, sym, bootstrap, widths
0 2
10 #FF0000
4 6 8 10 12 14 16 (R,G,B[,A]) Label 2 Label 4
1
borderpad
0 2 4 #FF0000BB
6 8 #FF000088
10 12 #FF000044
14 16 ’#RRGGBB[AA]’ Keyboard shortcuts
columnspacing numpoints or scatterpoints
10 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 API
0 2 4 6 8 10 12 14 16 ’x.y’
756 246 X,errorbar(X,Y,xerr,yerr,…)
borderaxespad
0
API 0 2 4 6 8 10 12 14 16
ctrl + s Save ctrl + w Close plot
G = gridspec(rows,cols,…) API
432 Y, xerr, yerr, fmt ax.colorbar(…) API r Reset view f Fullscreen 0/1
ax = G[0,:]
1 Colormaps API
mappable, ax, cax, orientation
f View forward b View back
71
61
51 1234567 X,hist(X, bins, …)
API plt.get_cmap(name) p Pan view o Zoom to rect
ax.inset_axes(extent) 41
31
21
API bins, range, density, weights
Uniform
0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0
x X pan/zoom y Y pan/zoom
111 viridis g Minor grid 0/1 G Major grid 0/1
756 1234567 violinplot(D,…) API magma ax.annotate(…) API
l X axis log/linear L Y axis log/linear

ax = d.new_horizontal(’10%’) 3
d=make_axes_locatable(ax) API
42 D, positions, widths, vert plasma
text, xy, xytext, xycoords, textcoords, arrowprops

1 Sequential
text Ten simple rules
765 1234567 barbs([X],[Y],
Greys READ
API U, V, …) YlOrBr xytext xy
4
textcoords xycoords
X, Y, U, V, C, length, pivot, sizes
231
Wistia 1. Know Your Audience
Getting help Diverging 2. Identify Your Message

6754 1234567 positions, orientation, lineoffsets


Spectral 3. Adapt the Figure
Å matplotlib.org eventplot(positions,…)
API
4. Captions Are Not Optional
coolwarm
Event handling API
H github.com/matplotlib/matplotlib/issues
ď discourse.matplotlib.org
321 Qualitative
RdGy

fig, ax = plt.subplots()
5. Do Not Trust the Defaults
6. Use Color Effectively
W stackoverflow.com/questions/tagged/matplotlib
Ż gitter.im/matplotlib
7
654 1234567 hexbin(X,Y,C,…) API
X, Y, C, gridsize, bins
tab10
tab20
def on_click(event):
print(event)
7. Do Not Mislead the Reader
8. Avoid “Chartjunk”
F twitter.com/matplotlib
a Matplotlib users mailing list
321 Cyclic
twilight
fig.canvas.mpl_connect(
’button_press_event’, on_click)
9. Message Trumps Beauty
10. Get the Right Tool
1234567
Axes adjustments API Uniform colormaps Color names API Legend placement How do I …
plt.subplots_adjust( … ) viridis
plasma
black
k
dimgray
dimgrey
gray
floralwhite
darkgoldenrod
goldenrod
cornsilk
gold
darkturquoise
cadetblue
powderblue
lightblue
deepskyblue
L K J … resize a figure?
→ fig.set_size_inches(w, h)
… save a figure?

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

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

bilinear bicubic spline16


angle, angle, arc,
coolwarm angleA=-90, angleA=-90, angleA=-90,
angleB=180, angleB=180, angleB=0,
center bwr rad=0 rad=25 armA=0,
armB=40,
baseline rad=0 scatter(X, Y) slow
bottom seismic 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 spline36 hanning hamming fraction=0.3 fraction=-0.3 angle=180,
fraction=-0.2 im.set_data(…), canvas.draw() fast
ax.text(…, family=…, size=…, weight=…) Pastel2
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) yt: Volumetric data Visualization
The quick brown fox
The quick brown fox
medium (1.00)
Set2
hermite kaiser quadric mpld3: Bringing Matplotlib to the browser
The quick brown fox
small
x-small
(0.83)
(0.69)
Set3
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 Copyright (c) 2021 Matplotlib Development Team
ultralight (100)

Miscellaneous colormaps
catrom gaussian bessel <|- -|> <|-|> ]-
Released under a CC‐BY 4.0 International License
The quick brown fox jumps over the lazy dog monospace
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
rainbow <-[ simple fancy wedge
The quick brown fox jumps over the lazy dog
The quick brown fox jumps over the lazy dog
small-caps
normal twilight mitchell sinc lanczos

You might also like