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

Matplotlib Cheat Sheet Guide

Cheatsheet for matplotib users (python 3)
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 views2 pages

Matplotlib Cheat Sheet Guide

Cheatsheet for matplotib users (python 3)
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

Basic plots Scales API Tick locators API Animation API

plot([X], Y, [fmt], …) API ax.set_[xy]scale(scale, …) from matplotlib import ticker import [Link] 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 = [Link](0, 2*[Link], 100)
S = [Link](T)
Quick start API scatter(X, Y, …) API symlog logit line, = [Link](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([Link](T+i/50))
import matplotlib as mpl anim = [Link](
import [Link] as plt bar[h](x, height, …) API
x, height, width, bottom, align, color
Projections API [Link](), animate, interval=5)
[Link]()
subplot(…, projection=p)
X = [Link](0, 2*[Link], 100) p=’polar’ p=’3d’ API
Y = [Link](X) imshow(Z, …) API Styles API
Z, cmap, interpolation, extent, origin
fig, ax = [Link]() [Link](style)
[Link](X, Y, color=’green’) contour[f]([X], [Y], Z, …) API p=[Link]() API
X, Y, Z, levels, colors, extent, origin import [Link] as ccrs
[Link](“[Link]”) Tick formatters API
[Link]()
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 [Link]()
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, …)
[Link](…) API ax.set_axis_[on|off]()
handles, labels, loc, title, frameon
Advanced plots [Link](title)
title
fig.tight_layout()
step(X, Y, [fmt], …) API
Colors API
Legend label [Link](), [Link]()
X, Y, fmt, color, marker, where handletextpad handle
handlelength
markerfacecolor (mfc)
[Link](’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 = [Link](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 [Link](…) 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
[Link](…) 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
[Link] eventplot(positions, …) API coolwarm 4. Captions are not optional
positions, orientation, lineoffsets RdGy
Event handling API
[Link]/matplotlib/matplotlib/issues 5. Do not trust the defaults
[Link] Qualitative fig, ax = [Link]() 6. Use color effectively
[Link]/questions/tagged/matplotlib hexbin(X, Y, C, …) API
tab10 def on_click(event): 7. Do not mislead the reader
[Link] tab20 print(event) 8. Avoid “chartjunk”
X, Y, C, gridsize, bins
[Link]/matplotlib Cyclic [Link].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 → [Link](”[Link]”)
magma … save a transparent figure?
cividis → [Link](”[Link]”, transparent=True)
… clear a figure/an axes?
→ [Link]() → [Link]()
Sequential colormaps
… close all figures?
→ [Link](”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 → [Link][’top’].set_visible(False)
OrRd … hide legend border?
PuRd → [Link](frameon=False)
Extent & origin API
RdPu
[Link](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)
[Link]( 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([Link]((0, 0), 1, 1)
YlGnBu
… draw a vertical line?
A: upper right / (-0.1, 0.9) B: center right / (-0.1, 0.5) → [Link](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) → [Link](…, 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) → [Link](…, 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 → [Link].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
[Link]( …, ha=… , va=…, …) → [Link](block=False), [Link](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(…); [Link]() slow


Pastel1 im.set_data(…); [Link]() fast
[Link](…, family=…, size=…, weight=…) Pastel2
[Link](…, 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