You are on page 1of 5

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


2.5 10 1 logit
0 + values > 0 ticker.NullLocator() T = np.linspace(0,2*np.pi,100)

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


API 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

2.5 1000100 2.5 1


Y, [s]izes, [c]olors, markers, cmap - any values
+ 0 < values < 1
0 1 ticker.FixedLocator([0, 1, 5]) def animate(i):
import numpy as np
1 0 1 5 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)

321 height, width, bottom, align, color


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) 0.0 1.5 3.0 4.5
API
Z, cmap, interpolation, extent, origin
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 1.0 1.0
from cartopy.crs import Cartographic
Tick formatters
3 X, Y, Z, levels, colors, extent, origin 0.5 0.5

21
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 7

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

3421
1.0 1.0 1.0

Anatomy of a figure
X, Y, U, V, C, units, angles Lines 0.5
0.5 0.5

API ticker.NullFormatter() 0.0 0.0 0.0


0.5 0.5 0.5

765 1234567 pie(X,[explode],…) linestyle or ls


1.0
ticker.FixedFormatter(['', '0', '1', ...]) 1.0 1.0
0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7

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
432
1.0
1.0 1.0
Z, explode, labels, colors, radius "-" ":" "--" "-." (0,(0.01,2)) ticker.FuncFormatter(lambda x, pos: "[%.2f]" % x)
4 0.5 0.5 0.5

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

Major tick Red signal 0.5 0.5 0.5

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


Legend ticker.FormatStrFormatter('>%d<') 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 7

text(x,y,text,…) API >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 API ticker.StrMethodFormatter('{x}')

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


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

432 ticker.PercentFormatter(xmax=5) ax.patch.set_alpha(0)


Y axis label

2 Y1, Y2, color, where 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
432
Line
(line plot) X, Y, fmt, color, marker, where 10 [0, -1] (25, 5) [0, 25, -1] title ax.set_axis_[on|off]()
0
1
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’
API 1 DarkRed Firebrick Crimson IndianRed Salmon borderpad
text=r’$\frac{-e^{i\pi}}{2^n}$’

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


’name’ columnspacing numpoints or scatterpoints
10 (1,0,0) (1,0,0,0.75) (1,0,0,0.5) (1,0,0,0.25)
312
subplot[s](cols,rows,…) API Y, xerr, yerr, fmt 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

41
ctrl + s Save ctrl + w Close plot

31
G = gridspec(cols,rows,…) API bins, range, density, weights mappable, ax, cax, orientation
ax = G[0,:]
21
111 Colormaps API
r Reset view f Fullscreen 0/1

765 1234567 violinplot(D,…) View forward


f b View back
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

423
ax.inset_axes(extent)
p Pan view o Zoom to rect
API D, positions, widths, vert

1 Uniform x X pan/zoom y Y pan/zoom


ax.annotate(…)
6754 1234567 barbs([X],[Y],
viridis API g Minor grid 0/1 G Major grid 0/1
U, V, …) API magma text, xy, xytext, xycoords, textcoords, arrowprops
l X axis log/linear L Y axis log/linear

321
d=make_axes_locatable(ax) plasma
API X, Y, U, V, C, length, pivot, sizes
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
hexbin(X,Y,C,…) API
matplotlib.org coolwarm
Event handling 4. Captions Are Not Optional
321
API
github.com/matplotlib/matplotlib/issues RdGy 5. Do Not Trust the Defaults

0.2500
discourse.matplotlib.org Qualitative fig, ax = plt.subplots() 6. Use Color Effectively
stackoverflow.com/matplotlib
0.1875
0.1250
0.0625 1234567 X, Y, normed, detrend
xcorr(X,Y,…) API
tab10 def on_click(event): 7. Do Not Mislead the Reader

0.0000
gitter.im/matplotlib tab20 print(event) 8. Avoid “Chartjunk”
twitter.com/matplotlib 0.0625
0.1250
0.1875
Cyclic fig.canvas.mpl_connect( 9. Message Trumps Beauty
Matplotlib users mailing list
0.2500 twilight ’button_press_event’, on_click) 10. Get the Right Tool
Axes adjustements API Uniform colormaps Color names API Legend placement How do I …
black floralwhite darkturquoise … resize a figure?
L K J
plt.subplot_adjust( … ) k darkgoldenrod cadetblue
viridis
dimgray goldenrod powderblue → fig.set_size_inches(w,h)
plasma dimgrey cornsilk lightblue
gray gold deepskyblue … save a figure?
grey lemonchiffon skyblue
→ fig.savefig(”figure.pdf”)
A 7 8 9 I
inferno
darkgray khaki lightskyblue
magma darkgrey palegoldenrod steelblue
silver darkkhaki aliceblue … save a transparent figure?
lightgray ivory dodgerblue
top axes width
cividis lightgrey beige lightslategray → fig.savefig(”figure.pdf”, transparent=True)
gainsboro lightyellow lightslategrey
whitesmoke lightgoldenrodyellow slategray … clear a figure?
w olive slategrey
→ ax.clear()
Sequential colormaps white
snow
y
yellow
lightsteelblue
cornflowerblue
rosybrown olivedrab royalblue … close all figures?
B 4 5 6 H

figure height
lightcoral yellowgreen ghostwhite
axes height indianred darkolivegreen lavender → plt.close(”all”)
Greys brown greenyellow midnightblue
firebrick chartreuse navy … remove ticks?
hspace Purples maroon lawngreen darkblue → ax.set_xticks([])
darkred honeydew mediumblue
Blues r darkseagreen b … remove tick labels ?
red palegreen blue
Greens mistyrose lightgreen slateblue → ax.set_[xy]ticklabels([])
salmon forestgreen darkslateblue

C 1 2 3 G
left bottom wspace right Oranges tomato limegreen mediumslateblue … rotate tick labels ?
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
D E F
figure width seashell mediumseagreen darkviolet
YlOrRd chocolate springgreen mediumorchid → ax.spines[’top’].set_visible(False)
OrRd saddlebrown mintcream thistle … hide legend border?
sandybrown mediumspringgreen plum
peachpuff mediumaquamarine violet → ax.legend(frameon=False)
Extent & origin API
PuRd peru
linen
aquamarine
turquoise
purple
darkmagenta ax.legend(loc=”string”, bbox_to_anchor=(x,y))
RdPu bisque lightseagreen m … show error as shaded region?
darkorange mediumturquoise fuchsia → ax.fill_between(X, Y+error, Y‐error)
ax.imshow( extent=…, origin=… ) BuPu burlywood azure magenta 1: lower left 2: lower center 3: lower right
antiquewhite lightcyan orchid … draw a rectangle?
GnBu tan paleturquoise mediumvioletred 4: left 5: center 6: right
navajowhite darkslategray deeppink → ax.add_patch(plt.Rectangle((0, 0),1,1)
origin="upper" origin="upper" PuBu blanchedalmond darkslategrey hotpink 7: upper left 8: upper center 9: upper right
5
(0,0) (0,0) papayawhip teal lavenderblush … draw a vertical line?
YlGnBu moccasin darkcyan palevioletred
orange c crimson A: upper right / (‐.1,.9) B: right / (‐.1,.5) → ax.axvline(x=0.5)
PuBuGn wheat aqua pink
oldlace cyan lightpink C: lower right / (‐.1,.1) D: upper left / (‐.1,‐.1) … draw outside frame?
BuGn E: upper center / (.5,‐.1) F: upper right / (.9,‐.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,.1) H: left / (1.1,.5)
Image interpolation API
I: upper left / (1.1,.9) J: lower right / (.9,1.1)
… use transparency?
5
origin="lower" origin="lower" → ax.plot(…, alpha=0.25)
(4,4) (4,4)
Diverging colormaps K: lower center / (.5,1.1) L: lower left / (.1,1.1) … convert an RGB image into a gray image?
→ gray = 0.2989*R+0.5870*G+0.1140*B
(0,0) (0,0) PiYG Annotation connection styles API … set figure background color?
0
extent=[0,10,0,5] extent=[10,0,0,5] PRGn
→ fig.patch.set_facecolor(“grey”)
0 10 0 10
BrBG
arc3, arc3, angle3, … get a reversed colormap?
None none nearest
rad=0 rad=0.3 angleA=0,
angleB=90
→ plt.get_cmap(“viridis_r”)
PuOr
… get a discrete colormap?
Text alignments API RdGy
→ plt.get_cmap(“viridis”, 10)
RdBu
ax.text( …, ha=… , va=…, … ) … show a figure for one second?
RdYlBu
→ fig.show(block=False), time.sleep(1)

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

Text parameters API Pastel1 spline36 hanning hamming cla(), imshow(…), canvas.draw() slow
im.set_data(…), canvas.draw() fast
Pastel2
ax.text( …, family=… , size=…, weight = …)
Paired
ax.text( …, fontproperties = … )
Accent Beyond Matplotlib
The quick brown fox xx-large (1.73)
Dark2

The quick brown fox x-large (1.44)


Set1
Annotation arrow styles
Seaborn: Statistical Data Visualization
The quick brown fox large (1.20) Set2
hermite kaiser quadric
API Cartopy: Geospatial Data Processing
The quick brown fox medium (1.00) Set3 yt: Volumetric data Visualization
The quick brown fox small (0.83)
mpld3: Bringing Matplotlib to the browser
The quick brown fox x-small (0.69) tab10 - <- ->
The quick brown fox xx-small (0.58)
tab20 Datashader: Large data processing pipeline
The quick brown fox jumps over the lazy dog black (900) tab20b
plotnine: A Grammar of Graphics for Python
The quick brown fox jumps over the lazy dog bold (700)
The quick brown fox jumps over the lazy dog semibold (600) tab20c <-> <|- -|>
The quick brown fox jumps over the lazy dog normal (400)
The quick brown fox jumps over the lazy dog ultralight (100)
Miscellaneous colormaps
catrom gaussian bessel Matplotlib Cheatsheets (c) 2020 Nicolas P. Rougier
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 -[ |-| simple
The quick brown fox jumps over the lazy dog italic
The quick brown fox jumps over the lazy dog normal cubehelix
rainbow
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 fancy wedge
Matplotlib for beginners
Matplotlib is a library for making 2D plots in Python. It is
Z = np.random.uniform(0, 1, (8,8) 765 Organize
designed with the philosophy that you should be able to
432 You can plot several data on the the same figure but you can
1
create simple plots with just a few commands:
ax.contourf(Z) also split a figure in several subplots (named Axes):
1 Initialize
Z = np.random.uniform(0, 1, 4) 765 1234567 765
432
X = np.linspace(0,10,100)
import numpy as np Y1, Y1 = np.sin(X), np.cos(X) 432
import matplotlib.pyplot as plt ax.pie(Z)
1 ax.plot(X, Y1, Y2)
1
Z = np.random.normal(0, 1, 100) 71
61
51 1234567 1234567
41 fig, (ax1, ax2) = plt.subplots((2,1))
2 Prepare
X = np.linspace(0, 4*np.pi, 1000) ax.hist(Z) 31
21
111
ax1.plot(X, Y1, color=”C1”)
ax2.plot(X, Y2, color=”C0”)
Y = np.sin(X)
X = np.arange(5) 765 1234567
432
fig, (ax1, ax2) = plt.subplots((1,2))
3 Render Y = np.random.uniform(0,1,5) ax1.plot(Y1, X, color=”C1”)
fig, ax = plt.subplots() ax.errorbar(X, Y, Y/4)
1 ax2.plot(Y2, X, color=”C0”)
ax.plot(X, Y)
Z = np.random.normal(0,1,(100,3)) 765 1234567
fig.show()
432 Label (everything)
4 Observe ax.boxplot(Z)
1 A Sine wave
1.0
246 ax.plot(X, Y)
fig.suptitle(None) 543
0.5
0.0
Tweak ax.set_title(”A Sine wave”) 21
0.5
1.0
You can modify pretty much anything in a plot, including lim-
its, colors, markers, line width and styles, ticks and ticks la-
ax.plot(X, Y) 1234567
ax.set_ylabel(None)
0 5 10 15 20 25 30 bels, titles, etc.
ax.set_xlabel(”Time”)

765
Time

Choose X = np.linspace(0,10,100)
Y = np.sin(X) 432 Explore
Matplotlib offers several kind of plots (see Gallery): ax.plot(X, Y, color=”black”)
1
765 765 1234567
Figures are shown with a graphical user interface that all-
X = np.random.uniform(0, 1, 100) X = np.linspace(0,10,100) lows to zoom and pan the figure, to navigate between the
Y = np.random.uniform(0, 1, 100) 432 Y = np.sin(X) 432 different views and to show the value under the mouse.
ax.scatter(X, Y)
1 ax.plot(X, Y, linestyle=”--”)
1
X = np.arange(10) 765 1234567 X = np.linspace(0,10,100) 765 1234567 Save (bitmap or vector format)
Y = np.random.uniform(1, 10, 10) 432 Y = np.sin(X) 432
ax.bar(X, Y)
1 ax.plot(X, Y, linewidth=5)
1 fig.savefig(”my-first-figure.png”, dpi=300)
fig.savefig(”my-first-figure.pdf”)
Z = np.random.uniform(0, 1, (8,8) 765 1234567 X = np.linspace(0,10,100) 765 1234567
432 Y = np.sin(X) 432
1 1
Matplotlib 3.2 handout for beginners. Copyright (c) 2020 Nicolas P. Rougier. Released
ax.imshow(Z) ax.plot(X, Y, marker=”o”) under a CC-BY International 4.0 License. Supported by NumFocus Grant #12345.

1234567 1234567
Matplotlib for intermediate users
A matplotlib figure is composed of a hierarchy of elements Ticks & labels Legend
that forms the actual figure. Each element can be modified.
from mpl.ticker import MultipleLocator as ML ax.plot(X, np.sin(X), ”C0”, label=”Sine”)
from mpl.ticker import ScalarFormatter as SF ax.plot(X, np.cos(X), ”C1”, label=”Cosine”)
4
Anatomy of a figure ax.xaxis.set_minor_locator(ML(0.2)) ax.legend(bbox_to_anchor=(0,1,1,.1),ncol=2,
Title Blue signal ax.xaxis.set_minor_formatter(SF()) mode=”expand”, loc=”lower left”)
Major tick Red signal ax.tick_params(axis=’x’,which=’minor’,rotation=90)
Legend Sine Sine and Cosine Cosine
Minor tick 0 1 2 3 4 5

0.2
0.4
0.6
0.8

1.2
1.4
1.6
1.8

2.2
2.4
2.6
2.8

3.2
3.4
3.6
3.8

4.2
4.4
4.6
4.8
3
Major tick label Grid Lines & markers
Line
(line plot)
X = np.linspace(0.1, 10*np.pi, 1000) Annotation
Y axis label

2 Y = np.sin(X)
ax.plot(X, Y, ”C1o:”, markevery=25, mec=”1.0”) ax.annotate(”A”, (X[250],Y[250]),(X[250],-1),
Y axis label ha=”center”, va=”center”,arrowprops =
Markers
(scatter plot) 1 {”arrowstyle” : ”->”, ”color”: ”C1”})
0
1 1 1
0 5 10 15 20 25 30 0
Spines 1 A
Figure Line 0 5 10 15 20 25 30
Axes (line plot) Scales & Projections
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
X axis label fig, ax = plt.subplots() Colors
Minor tick label
X axis label ax.set_xscale(”log”)
ax.plot(X, Y, ”C1o-”, markevery=25, mec=”1.0”) 1 AnyC0
color can be used but Matplotlib offers sets of colors:
C1 C2 C3 C4 C5 C6 C7 C8 C9
10 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0
Figure, axes & spines
1 0 2 4 6 8 10 12 14 16
0 0
1
0 2 4 6 8 10 12 14 16
fig, axs = plt.subplots((3,3)) 10 1 100 101
axs[0,0].set_facecolor(”#ddddff”) Size & DPI
axs[2,2].set_facecolor(”#ffffdd”) Text & Ornaments Consider a square figure to be included in a two-columns A4
paper with 2cm margins on each side and a column separa-
gs = fig.add_gridspec(3, 3)
ax.fill_betweenx([-1,1],[0],[2*np.pi]) tion of 1cm. The width of a figure is (21 - 2*2 - 1)/2 = 8cm.
ax = fig.add_subplot(gs[0, :])
ax.text(0, -1, r” Period $\Phi$”) One inch being 2.54cm, figure size should be 3.15×3.15 in.
ax.set_facecolor(”#ddddff”)
1 fig = plt.figure(figsize=(3.15,3.15), dpi=50)
fig, ax = plt.subplots() 0 plt.savefig(”figure.pdf”, dpi=600)
ax.spines[”top”].set_color(”None”) 1 Period
Matplotlib 3.2 handout for intermediate users. Copyright (c) 2020 Nicolas P. Rougier.
ax.spines[”right”].set_color(”None”) 0 5 10 15 20 25 30 Released under a CC-BY 4.0 License. Supported by NumFocus Grant #12345.
Matplotlib tips & tricks
Transparency Text outline Colorbar adjustment
Scatter plots can be enhanced by using transparency (al- Use text outline to make text more visible. You can adjust colorbar aspect when adding it.
pha) in order to show area with higher density and multiple
import matplotlib.patheffects as fx im = ax.imshow(Z)
scatter plots can be used to delineate a frontier. text = ax.text(0.5, 0.1, ”Label”)
text.set_path_effects([ cb = plt.colorbar(im,
X = np.random.normal(-1,1,500) fx.Stroke(linewidth=3, foreground=’1.0’), fraction=0.046, pad=0.04)
Y = np.random.normal(-1,1,500) fx.Normal()]) cb.set_ticks([])
ax.scatter(X, Y, 50, ”0.0”, lw=2) # optional
ax.scatter(X, Y, 50, ”1.0”, lw=0) # optional
ax.scatter(X, Y, 40, ”C1”, lw=0, alpha=0.1)
Multiline plot Taking advantage of typography
You can use a condensed face such as Roboto Condensed
You can plot several lines at once using None as separator.
Rasterization to save space on tick labels.
X,Y = [], []
for tick in ax.get_xticklabels(which=’both’):
If your figure is made of a lot graphical elements such as a for x in np.linspace(0, 10*np.pi, 100):
tick.set_fontname(”Roboto Condensed”)
huge scatter, you can rasterize them to save memory and X.extend([x, x, None]), Y.extend([0, sin(x), None])
ax.plot(X, Y, ”black”)
keep other elements in vector format.                    
     
X = np.random.normal(-1, 1, 10_000)
Y = np.random.normal(-1, 1, 10_000)
ax.scatter(X, Y, rasterized=True) Getting rid of margins
fig.savefig(”rasterized-figure.pdf”, dpi=600)
Once your figure is finished, you can call tight_layout()
to remove white margins. If there are remaining margins,
Dotted lines you can use the pdfcrop utility (comes with TeX live).
Offline rendering To have rounded dotted lines, use a custom linestyle and
modify dash_capstyle. Hatching
Use the Agg backend to render a figure directly in an array.
ax.plot([0,1], [0,0], ”C1”, You can achieve nice visual effect with thick hatch patterns.
from matplotlib.backends.backend_agg import FigureCanvas linestyle = (0, (0.01, 1)), dash_capstyle=”round”) 59%
canvas = FigureCanvas(Figure())) ax.plot([0,1], [1,1], ”C1”, cmap = plt.get_cmap(”Oranges”)
53%

... # draw som stuff linestyle = (0, (0.01, 2)), dash_capstyle=”round”) plt.rcParams[’hatch.color’] = cmap(0.2)
38%

canvas.draw() plt.rcParams[’hatch.linewidth’] = 8
27%

Z = np.array(canvas.renderer.buffer_rgba()) ax.bar(X, Y, color=cmap(0.6), hatch=”/” )


2018 2019

Read the documentation


Range of continuous colors Combining axes
Matplotlib comes with an extensive documenation explain-
You can use colormap to pick a range of continuous colors. You can use overlaid axes with different projections. ing every detals of each command and is generally accom-
X = np.random.randn(1000, 4) ax1 = fig.add_axes([0,0,1,1],
panied by examples with. Together with the huge online
cmap = plt.get_cmap(”Blues”) label=”cartesian”) gallery, this documenation is a gold-mine.
colors = [cmap(i) for in in [.2,.4,.6,.8]] ax2 = fig.add_axes([0,0,1,1],
label=”polar”,
Matplotlib 3.2 handout for tips & tricks. Copyright (c) 2020 Nicolas P. Rougier. Re-
ax.hist(X, 2, histtype=’bar’, color=colors) projection=”polar”)
leased under a CC-BY 4.0 License. Supported by NumFocus Grant #12345.

You might also like