0% found this document useful (0 votes)
14 views5 pages

matplotlib full

This document serves as a comprehensive cheat sheet for Matplotlib, detailing various plotting functions, scales, tick locators, and animation capabilities. It includes examples of basic and advanced plots, customization options, and color maps, along with API references for each feature. Additionally, it provides guidance on figure anatomy, layout, and best practices for effective data visualization.

Uploaded by

codeyandlogic
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views5 pages

matplotlib full

This document serves as a comprehensive cheat sheet for Matplotlib, detailing various plotting functions, scales, tick locators, and animation capabilities. It includes examples of basic and advanced plots, customization options, and color maps, along with API references for each feature. Additionally, it provides guidance on figure anatomy, layout, and best practices for effective data visualization.

Uploaded by

codeyandlogic
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

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.7.4 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

plt.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-v0_8 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-v0_8-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
Diverging colormaps K: lower center / (0.5, 1.1) L: lower left / (0.1, 1.1) … convert an RGB image into a gray image?
5
(4,4) (4,4)
→ 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(i, X[i], ”o”) slow
Qualitative colormaps plot(X, marker=”o”, ls=””) 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
Matplotlib for beginners
Matplotlib is a library for making 2D plots in Python. It is
Z = np.random.uniform(0, 1, (8, 8))
Organize
designed with the philosophy that you should be able to
create simple plots with just a few commands: You can plot several data on the same figure, but you can
ax.contourf(Z) also split a figure in several subplots (named Axes):
1 Initialize
Z = np.random.uniform(0, 1, 4) X = np.linspace(0, 10, 100)
import numpy as np Y1, Y2 = np.sin(X), np.cos(X)
import matplotlib.pyplot as plt ax.pie(Z) ax.plot(X, Y1, X, Y2)

Z = np.random.normal(0, 1, 100) fig, (ax1, ax2) = plt.subplots(2, 1)


2 Prepare
ax1.plot(X, Y1, color=”C1”)
X = np.linspace(0, 10*np.pi, 1000) ax.hist(Z) ax2.plot(X, Y2, color=”C0”)
Y = np.sin(X)
X = np.arange(5) fig, (ax1, ax2) = plt.subplots(1, 2)
3 Render Y = np.random.uniform(0, 1, 5) ax1.plot(Y1, X, color=”C1”)
ax.errorbar(X, Y, Y∕4) ax2.plot(Y2, X, color=”C0”)
fig, ax = plt.subplots()
ax.plot(X, Y) Z = np.random.normal(0, 1, (100, 3))
plt.show() Label (everything)
ax.boxplot(Z)
4 Observe A Sine wave
ax.plot(X, Y)
1.0 fig.suptitle(None)
0.5 Tweak ax.set_title(”A Sine wave”)
0.0
0.5 You can modify pretty much anything in a plot, including lim-
ax.plot(X, Y)
1.0 its, colors, markers, line width and styles, ticks and ticks la-
0 5 10 15 20 25 30 ax.set_ylabel(None)
bels, titles, etc.
ax.set_xlabel(”Time”)
Time

Choose X = np.linspace(0, 10, 100)


Y = np.sin(X) Explore
Matplotlib offers several kind of plots (see Gallery): ax.plot(X, Y, color=”black”)
Figures are shown with a graphical user interface that al-
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) Y = np.sin(X) different views and to show the value under the mouse.
ax.scatter(X, Y) ax.plot(X, Y, linestyle=”--”)
Save (bitmap or vector format)
X = np.arange(10) X = np.linspace(0, 10, 100)
Y = np.random.uniform(1, 10, 10) Y = np.sin(X)
ax.bar(X, Y) ax.plot(X, Y, linewidth=5) fig.savefig(”my-first-figure.png”, dpi=300)
fig.savefig(”my-first-figure.pdf”)
Z = np.random.uniform(0, 1, (8, 8)) X = np.linspace(0, 10, 100)
Y = np.sin(X)
Matplotlib 3.7.4 handout for beginners. Copyright (c) 2021 Matplotlib Development
ax.imshow(Z) ax.plot(X, Y, marker=”o”) Team. Released under a CC-BY 4.0 International License. Supported by NumFOCUS.
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())
Major tick Red signal
mode=”expand”, loc=”lower left”)
ax.tick_params(axis=’x’,which=’minor’,rotation=90)
Legend Sine and Cosine
Sine 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
Line
Lines & markers
(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=50, mec=”1.0”) ax.annotate(”A”, (X[250],Y[250]), (X[250],-1),
Y axis label Markers
ha=”center”, va=”center”, arrowprops={
(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 Colors
Minor tick label
X axis label fig, ax = plt.subplots()
X axis label ax.set_xscale(”log”)
ax.plot(X, Y, ”C1o-”, markevery=50, 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
10 1 100 101
fig, axs = plt.subplots(3, 3) Size & DPI
axs[0, 0].set_facecolor(”#ddddff”)
axs[2, 2].set_facecolor(”#ffffdd”) Consider a square figure to be included in a two-column A4
Text & ornaments
paper with 2 cm margins on each side and a column separa-
gs = fig.add_gridspec(3, 3) tion of 1 cm. The width of a figure is (21 - 2*2 - 1)/2 = 8 cm.
ax.fill_betweenx([-1, 1], [0], [2*np.pi])
ax = fig.add_subplot(gs[0, :]) One inch being 2.54 cm, figure size should be 3.15×3.15 in.
ax.text(0, -1, r” Period $\Phi$”)
ax.set_facecolor(”#ddddff”)
fig = plt.figure(figsize=(3.15, 3.15), dpi=50)
1 plt.savefig(”figure.pdf”, dpi=600)
fig, ax = plt.subplots() 0
ax.spines[”top”].set_color(”None”) 1 Period
Matplotlib 3.7.4 handout for intermediate users. Copyright (c) 2021 Matplotlib De-
velopment Team. Released under a CC-BY 4.0 International License. Supported by
ax.spines[”right”].set_color(”None”) 0 5 10 15 20 25 30 NumFOCUS.
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 a colorbar’s size when adding it.
pha) in order to show area with higher density. Multiple scat-
import matplotlib.patheffects as fx im = ax.imshow(Z)
ter 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 plot several lines at once using None as separator. You can use a condensed font such as Roboto Condensed
Rasterization to save space on tick labels.
X,Y = [], []
If your figure has many graphical elements, such as a huge for x in np.linspace(0, 10*np.pi, 100): for tick in ax.get_xticklabels(which=’both’):
X.extend([x, x, None]), Y.extend([0, sin(x), None]) tick.set_fontname(”Roboto Condensed”)
scatter, you can rasterize them to save memory and keep ax.plot(X, Y, ”black”)
other elements in vector format. 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
0 1 2 3 4 5
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
Use the Agg backend to render a figure directly in an array. Hatching
modify dash_capstyle.
from matplotlib.backends.backend_agg import FigureCanvas
ax.plot([0, 1], [0, 0], ”C1”,
You can achieve a nice visual effect with thick hatch pat-
canvas = FigureCanvas(Figure())) terns.
linestyle=(0, (0.01, 1)), dash_capstyle=”round”)
... # draw some stuff 59%
ax.plot([0, 1], [1, 1], ”C1”, 53%
canvas.draw() cmap = plt.get_cmap(”Oranges”)
linestyle=(0, (0.01, 2)), dash_capstyle=”round”) 38%
Z = np.array(canvas.renderer.buffer_rgba()) plt.rcParams[’hatch.color’] = cmap(0.2) 27%
plt.rcParams[’hatch.linewidth’] = 8
ax.bar(X, Y, color=cmap(0.6), hatch=”∕”)
2018 2019

Range of continuous colors


Combining axes Read the documentation
You can use colormap to pick from a range of continuous
colors. You can use overlaid axes with different projections. Matplotlib comes with an extensive documentation explain-
ing the details of each command and is generally accom-
X = np.random.randn(1000, 4) ax1 = fig.add_axes([0, 0, 1, 1],
cmap = plt.get_cmap(”Oranges”) label=”cartesian”)
panied by examples. Together with the huge online gallery,
colors = cmap([0.2, 0.4, 0.6, 0.8]) ax2 = fig.add_axes([0, 0, 1, 1], this documentation is a gold-mine.
label=”polar”,
Matplotlib 3.7.4 handout for tips & tricks. Copyright (c) 2021 Matplotlib Development
ax.hist(X, 2, histtype=’bar’, color=colors) projection=”polar”)
Team. Released under a CC-BY 4.0 International License. Supported by NumFOCUS.

You might also like