Download as pdf or txt
Download as pdf or txt
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
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 T = np.linspace(0, 2*np.pi, 100)
S = np.sin(T)
Quick start API scatter(X, Y, …) API symlog logit line, = plt.plot(T, S)
X, Y, [s]izes, [c]olors, marker, cmap any values 0 < values < 1 def animate(i):
import numpy as np line.set_ydata(np.sin(T+i/50))
import matplotlib as mpl anim = mpla.FuncAnimation(
import matplotlib.pyplot as plt bar[h](x, height, …) API
x, height, width, bottom, align, color
Projections API plt.gcf(), animate, interval=5)
plt.show()
subplot(…, projection=p)
X = np.linspace(0, 2*np.pi, 100) p=’polar’ p=’3d’ API
Y = np.cos(X) imshow(Z, …) API Styles API
Z, cmap, interpolation, extent, origin
fig, ax = plt.subplots() plt.style.use(style)
ax.plot(X, Y, color=’green’) contour[f]([X], [Y], Z, …) API p=ccrs.Orthographic() API
X, Y, Z, levels, colors, extent, origin import cartopy.crs as ccrs
fig.savefig(“figure.pdf”) Tick formatters API
plt.show()
pcolormesh([X], [Y], Z, …) API from matplotlib import ticker
ax.[xy]axis.set_[minor|major]_formatter(formatter)
Anatomy of a figure X, Y, Z, vmin, vmax, cmap
Lines API

quiver([X], [Y], U, V, …) API


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

pie(X, …) API
Z, explode, labels, colors, radius
Quick reminder
Markers API
text(x, y, text, …) API ax.grid()
x, y, text, va, ha, size, weight, transform ax.set_[xy]lim(vmin, vmax)
ax.set_[xy]label(label)
ax.set_[xy]ticks(ticks, [labels])
fill[_between][x](…) API ax.set_[xy]ticklabels(labels)
X, Y1, Y2, color, where Ornaments ax.set_title(title)
ax.tick_params(width=10, …)
ax.legend(…) API ax.set_axis_[on|off]()
handles, labels, loc, title, frameon
Advanced plots fig.suptitle(title)
title
fig.tight_layout()
step(X, Y, [fmt], …) API
Colors API
Legend label plt.gcf(), plt.gca()
X, Y, fmt, color, marker, where handletextpad handle
handlelength
markerfacecolor (mfc)
mpl.rc(’axes’, linewidth=1, …)
’Cn’ Label 1 Label 3 [fig|ax].patch.set_alpha(0)
Subplots layout API ’x’ labelspacing
text=r’$\frac{-e^{i\pi}}{2^n}$’
boxplot(X, …) API
markeredgecolor (mec)

X, notch, sym, bootstrap, widths


’name’ Label 2 Label 4
subplot[s](rows, cols, …) API (R,G,B[,A]) borderpad columnspacing numpoints or scatterpoints
fig, axs = plt.subplots(3, 3) ’#RRGGBB[AA]’
borderaxespad
Keyboard shortcuts API
’x.y’
errorbar(X,Y,xerr,yerr, …) API
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
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
plasma l X axis log/linear L Y axis log/linear
d=make_axes_locatable(ax) API D, positions, widths, vert text, xy, xytext, xycoords, textcoords, arrowprops
ax = d.new_horizontal(’10%’) Sequential
Greys Ten simple rules READ
barbs([X], [Y], U, V, …) API YlOrBr
X, Y, U, V, C, length, pivot, sizes Wistia 1. Know your audience
Getting help Diverging 2. Identify your message
Spectral 3. Adapt the figure
matplotlib.org eventplot(positions, …) API coolwarm 4. Captions are not optional
positions, orientation, lineoffsets RdGy
Event handling API
github.com/matplotlib/matplotlib/issues 5. Do not trust the defaults
discourse.matplotlib.org Qualitative fig, ax = plt.subplots() 6. Use color effectively
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 tab20 print(event) 8. Avoid “chartjunk”
X, Y, C, gridsize, bins
twitter.com/matplotlib Cyclic fig.canvas.mpl_connect( 9. Message trumps beauty
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( … ) … resize a figure?
viridis
→ fig.set_size_inches(w, h)
plasma … save a figure?
inferno → fig.savefig(”figure.pdf”)
magma … save a transparent figure?
cividis → fig.savefig(”figure.pdf”, transparent=True)
… clear a figure/an axes?
→ fig.clear() → ax.clear()
Sequential colormaps
… close all figures?
→ plt.close(”all”)
Greys
… remove ticks?
Purples
→ ax.set_[xy]ticks([])
Blues … remove tick labels ?
Greens → ax.set_[xy]ticklabels([])
Oranges … rotate tick labels ?
Reds → ax.tick_params(axis=”x”, rotation=90)
YlOrBr … hide top spine?
YlOrRd → ax.spines[’top’].set_visible(False)
OrRd … hide legend border?
PuRd → ax.legend(frameon=False)
Extent & origin API
RdPu
ax.legend(loc=”string”, bbox_to_anchor=(x, y)) … show error as shaded region?
BuPu 2: upper left 9: upper center 1: upper right → ax.fill_between(X, Y+error, Y‐error)
ax.imshow( extent=…, origin=… )
GnBu 6: center left 10: center 7: center right … draw a rectangle?
PuBu 3: lower left 8: lower center 4: lower right → ax.add_patch(plt.Rectangle((0, 0), 1, 1)
YlGnBu
… draw a vertical line?
A: upper right / (-0.1, 0.9) B: center right / (-0.1, 0.5) → ax.axvline(x=0.5)
PuBuGn
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) → ax.plot(…, clip_on=False)
YlGn 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)
Image interpolation API K: lower center / (0.5, 1.1) L: lower left / (0.1, 1.1)
Diverging colormaps … convert an RGB image into a gray image?
→ gray = 0.2989*R + 0.5870*G + 0.1140*B
PiYG … set figure background color?
PRGn Annotation connection styles API → fig.patch.set_facecolor(“grey”)
BrBG
… get a reversed colormap?
→ plt.get_cmap(“viridis_r”)
PuOr
… get a discrete colormap?
RdGy
Text alignments API
RdBu
→ plt.get_cmap(“viridis”, 10)
… show a figure for one second?
RdYlBu
ax.text( …, ha=… , va=…, …) → fig.show(block=False), time.sleep(1)
RdYlGn
Spectral
coolwarm
Performance tips
bwr
scatter(X, Y) slow
seismic plot(X, Y, marker=”o”, ls=””) fast
for i in range(n): plot(i, X[i], ”o”) slow
Qualitative colormaps plot(X, marker=”o”, ls=””) fast

Text parameters API cla(); imshow(…); canvas.draw() slow


Pastel1 im.set_data(…); canvas.draw() fast
ax.text(…, family=…, size=…, weight=…) Pastel2
ax.text(…, fontproperties=…) Paired Beyond Matplotlib
Accent
Dark2 Seaborn: Statistical data visualization
Set1 Cartopy: Geospatial data processing
Set2 yt: Volumetric data visualization
Set3 mpld3: Bringing Matplotlib to the browser
Annotation arrow styles API
Datashader: Large data processing pipeline
tab10
tab20 plotnine: A grammar of graphics for Python
tab20b
tab20c
Matplotlib Cheatsheets
Copyright (c) 2021 Matplotlib Development Team
Miscellaneous colormaps Released under a CC‐BY 4.0 International License

terrain
ocean
cubehelix
rainbow
twilight

You might also like