Scales Basic plots Version 3.5.0 API API ax.set_[xy]scale(scale,…) linear log + any values 0 + values > 0 API - Tick locators API 756 0.0 0.0 432 1 2.5 2.510102101 0logit 2 0 2 symlog Quick start 765 1234567 X,scatter(X,Y,…) 0.0 0.0 Y, [s]izes, [c]olors, marker, cmap 423 2.5 1000100any values2.5 1 0 < values < 1 import numpy as np 1 import matplotlib as mpl 2 import matplotlib.pyplot as plt 756 1234567 x,bar[h](x,height,…) Projections height, width, bottom, align, color 432 subplot(…,projection=p) 1 p=’polar’ X = np.linspace(0, 2*np.pi, 100) p=’3d’ 765 1234567 imshow(Z,…) Y = np.cos(X) Z, cmap, interpolation, extent, origin 3421 fig, ax = plt.subplots() p=Orthographic() ax.plot(X, Y, color=’green’) from cartopy.crs import Cartographic 6754 1234567 contour[f]([X],[Y],Z,…) X, Y, Z, levels, colors, extent, origin fig.savefig(“figure.pdf”) 3 21 fig.show() 32 1234567 pcolormesh([X],[Y],Z,…) 10 X, Y, Z, vmin, vmax, cmap Anatomy of a figure Lines 12 Anatomy of a figure linestyle or ls 7653 3210123 quiver([X],[Y],U,V,…) X, Y, U, V, C, units, angles 432 capstyle or dash_capstyle 1 pie(X,…) 765 1234567 Z, explode, labels, colors, radius 432 Markers 1 765 1234567T x,text(x,y,text,…) 432 TEX y, text, va, ha, size, weight, transform 1 756 1234567 X,fill[_between][x](…) Y1, Y2, color, where 432 1 markevery 1234567 10 [0, -1] (25, 5) [0, 25, -1] Advanced plots step(X,Y,[fmt],…) 765 Colors X, Y, fmt, color, marker, where 432 1 Subplots layout 765 1234567 X,boxplot(X,…) notch, sym, bootstrap, widths subplot[s](rows,cols,…) 42 fig, axs = plt.subplots(3, 3) 3 1 756 246 X,errorbar(X,Y,xerr,yerr,…) Y, xerr, yerr, fmt G = gridspec(rows,cols,…) 432 Colormaps ax = G[0,:] 1 bins, …) plt.get_cmap(name) 71 1234567 X,hist(X, 61 bins, range, density, weights 51 ax.inset_axes(extent) 41 Uniform 31 21 111 756 1234567 violinplot(D,…) D, positions, widths, vert d=make_axes_locatable(ax) 42 Sequential ax = d.new_horizontal(’10%’) 3 1 U, V, …) 765 1234567 barbs([X],[Y], X, Y, U, V, C, length, pivot, sizes 4 Diverging 231 Getting help eventplot(positions,…) Å matplotlib.org 6754 1234567 positions, orientation, lineoffsets H github.com/matplotlib/matplotlib/issues 321 ď discourse.matplotlib.org Qualitative W stackoverflow.com/questions/tagged/matplotlib hexbin(X,Y,C,…) 7 1234567 654 Ż gitter.im/matplotlib X, Y, C, gridsize, bins F twitter.com/matplotlib Cyclic 321 a Matplotlib users mailing list 1234567 Cheat sheet plot([X],Y,[fmt],…) X, Y, fmt, color, marker, linestyle + 0 1 API API API API API ticker.MultipleLocator(0.5) 0.0 0.5 4 Title Major tick Blue signal Red signal Legend Minor tick API "-" Major tick label "--" "butt" API 3 ":" "-." "round" (0,(0.01,2)) "projecting" Grid Y axis label Line (line plot) API API 2 Y axis label Markers (scatter plot) API 1 Figure 0 '.' 'o' 's' 'P' 'X' '*' 'p' 'D' '<' '>' '^' 'v' '1' '2' '3' '4' '+' 'x' '|' '_' 4 5 6 7 '$ $''$ $''$ $''$ $''$ $''$ $''$ $''$ $''$ $''$ $''$ $''$ $' Axes Line (line plot) Spines 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 Minor tick label X axis label API API API API API API API 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 1 5 ticker.LinearLocator(numticks=3) 0.0 2.5 5.0 ticker.IndexLocator(base=0.5, offset=0.25) 0.25 0.75 1.25 1.75 2.25 2.75 3.25 ticker.AutoLocator() 0 1 2 3.75 3 ticker.MaxNLocator(n=4) 0.0 1.5 4.25 4.75 4 5 3.0 104 105 107 106 108 API viridis magma plasma API Greys YlOrBr Wistia API API API Spectral coolwarm RdGy tab10 tab20 twilight T = np.linspace(0, 2*np.pi, 100) S = np.sin(T) line, = plt.plot(T, S) def animate(i): line.set_ydata(np.sin(T+i/50)) anim = mpla.FuncAnimation( plt.gcf(), animate, interval=5) plt.show() API plt.style.use(style) 109 1010 default 1.0 Tick formatters API 0.5 0.0 0.0 0.5 0.5 0 1 2 3 4 5 6 ggplot 1.0 ]) 2 3 4 5 6 bmh 0.5 0.0 0.5 0.5 four [4.00] [5.00] >3< >4< >5< 3 4 5 1.0 6 7 0 1 2 3 4 5 6 1.0 1.0 0 1 2 3 4 5 6 4 5 6 fast 1.0 0.5 0.0 0.5 1.0 1 2 3 4 5 6 Solarize_Light2 1.0 0.0 three [3.00] 5 seaborn 0 0.5 two [2.00] 4 1.0 five one [1.00] 3 0.0 1 ticker.FuncFormatter(lambda x, pos: "[%.2f]" % x) zero 2 0.5 0 1.0 [0.00] 1 0.5 0.5 ticker.FixedFormatter(['zero', 'one', 'two', 0.5 0 1.0 0.5 1.0 1.0 grayscale 1.0 0.5 0.0 0.0 ticker.NullFormatter() classic 1.0 0.5 1.0 from matplotlib import ticker ax.[xy]axis.set_[minor|major]_formatter(formatter) 0 1 2 3 seaborn-notebook 1.0 0.5 0.0 0.5 1.0 0 1 2 3 4 5 6 0 1 2 3 4 5 6 ticker.FormatStrFormatter('>%d<') >0< >1< >2< ticker.ScalarFormatter() 1 0 2 Quick reminder ticker.StrMethodFormatter('{x}') 0.0 1.0 2.0 3.0 4.0 5.0 80% 100% ticker.PercentFormatter(xmax=5) 0% 20% 40% 60% Ornaments ax.legend(…) handles, labels, loc, title, frameon API Legend label handletextpad handlelength handle markerfacecolor (mfc) Label 1 Label 3 labelspacing markeredgecolor (mec) Label 2 borderpad Label 4 Keyboard shortcuts numpoints or scatterpoints columnspacing borderaxespad ax.colorbar(…) mappable, ax, cax, orientation 0.0 0.1 0.2 0.3 0.4 0.5 0.6 API text ctrl + s Save r f 0.7 0.8 0.9 1.0 ax.annotate(…) API text, xy, xytext, xycoords, textcoords, arrowprops xytext textcoords ax.grid() ax.set_[xy]lim(vmin, vmax) ax.set_[xy]label(label) ax.set_[xy]ticks(ticks, [labels]) ax.set_[xy]ticklabels(labels) ax.set_title(title) ax.tick_params(width=10, …) ax.set_axis_[on|off]() fig.suptitle(title) fig.tight_layout() plt.gcf(), plt.gca() mpl.rc(’axes’, linewidth=1, …) [fig|ax].patch.set_alpha(0) text=r’$\frac{-e^{i\pi}}{2^n}$’ title API API API Styles 4.5 ticker.LogLocator(base=10, numticks=15) 103 API 1 C0 C1 C2 C3 C4 C5 C6 C7 C8 C9 ’Cn’ 0 0 b 2 g 4 r 6 c 8 m 10 y 12 k 14 w 16 ’x’ 1 DarkRed Firebrick Crimson IndianRed Salmon ’name’ 10 (1,0,0) (1,0,0,0.75) (1,0,0,0.5) (1,0,0,0.25) 0 2 4 6 8 10 12 14 16 (R,G,B[,A]) 10 #FF0000 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 0 2 4 6 8 10 12 14 16 ’x.y’ 0 0 2 4 6 8 10 12 14 16 1.0 ticker.FixedLocator([0, 1, 5]) 0 Animation import matplotlib.animation as mpla ticker.NullLocator() API API API from matplotlib import ticker ax.[xy]axis.set_[minor|major]_locator(locator) xy xycoords Event handling fig, ax = plt.subplots() def on_click(event): print(event) fig.canvas.mpl_connect( ’button_press_event’, on_click) API p x g l Reset view View forward Pan view X pan/zoom Minor grid 0/1 X axis log/linear API ctrl + w Close plot f Fullscreen 0/1 b View back o Zoom to rect y Y pan/zoom G Major grid 0/1 L Y axis log/linear Ten simple rules 1. Know Your Audience 2. Identify Your Message 3. Adapt the Figure 4. Captions Are Not Optional 5. Do Not Trust the Defaults 6. Use Color Effectively 7. Do Not Mislead the Reader 8. Avoid “Chartjunk” 9. Message Trumps Beauty 10. Get the Right Tool READ Axes adjustments API Color names Uniform colormaps plt.subplots_adjust( … ) viridis plasma inferno magma top axes width cividis axes height figure height Sequential colormaps hspace Greys Purples Blues Greens bottom left wspace right Oranges Reds YlOrBr figure width YlOrRd OrRd Extent & origin PuRd API RdPu ax.imshow( extent=…, origin=… ) 5 (0,0) origin="upper" BuPu GnBu origin="upper" PuBu (0,0) YlGnBu PuBuGn 0 extent=[0,10,0,5] origin="lower" 5 (0,0) 0 (4,4) (4,4) (4,4) (4,4) extent=[0,10,0,5] BuGn origin="lower" 10 darkturquoise cadetblue powderblue lightblue deepskyblue skyblue lightskyblue steelblue aliceblue dodgerblue lightslategray lightslategrey slategray slategrey lightsteelblue cornflowerblue royalblue ghostwhite lavender midnightblue navy darkblue mediumblue b blue slateblue darkslateblue mediumslateblue mediumpurple rebeccapurple blueviolet indigo darkorchid darkviolet mediumorchid thistle plum violet purple darkmagenta m fuchsia magenta orchid mediumvioletred deeppink hotpink lavenderblush palevioletred crimson pink lightpink Image interpolation API PiYG (0,0) 0 BrBG Text alignments How do I … L A 2 K 9 J 1 B 6 10 7 H C 3 D 8 E 4 G F I ax.legend(loc=”string”, bbox_to_anchor=(x,y)) 2: upper left 6: center left 3: lower left 9: upper center 10: center 8: lower center A: upper right / (-0.1,0.9) 1: upper right 7: center right 4: lower right B: center right / (-0.1,0.5) C: lower right / (-0.1,0.1) D: upper left / (0.1,-0.1) E: upper center / (0.5,-0.1) F: upper right / (0.9,-0.1) G: lower left / (1.1,0.1) H: center left / (1.1,0.5) I: upper left / (1.1,0.9) J: lower right / (0.9,1.1) K: lower center / (0.5,1.1) L: lower left / (0.1,1.1) None none nearest bilinear bicubic spline16 arc3, rad=0 arc3, rad=0.3 angle3, angleA=0, angleB=90 angle, angleA=-90, angleB=180, rad=0 angle, angleA=-90, angleB=180, rad=25 arc, angleA=-90, angleB=0, armA=0, armB=40, rad=0 API RdGy API RdBu ax.text( …, ha=… , va=…, …) RdYlBu Matplotlib RdYlGn (1,1) center Legend placement Annotation connection styles PRGn 10 PuOr (0,0) left API floralwhite darkgoldenrod goldenrod cornsilk gold lemonchiffon khaki palegoldenrod darkkhaki ivory beige lightyellow lightgoldenrodyellow olive y yellow olivedrab yellowgreen darkolivegreen greenyellow chartreuse lawngreen honeydew darkseagreen palegreen lightgreen forestgreen limegreen darkgreen g green lime seagreen mediumseagreen springgreen mintcream mediumspringgreen mediumaquamarine aquamarine turquoise lightseagreen mediumturquoise azure lightcyan paleturquoise darkslategray darkslategrey teal darkcyan c aqua cyan Diverging colormaps extent=[10,0,0,5] 0 YlGn extent=[10,0,0,5] black k dimgray dimgrey gray grey darkgray darkgrey silver lightgray lightgrey gainsboro whitesmoke w white snow rosybrown lightcoral indianred brown firebrick maroon darkred r red mistyrose salmon tomato darksalmon coral orangered lightsalmon sienna seashell chocolate saddlebrown sandybrown peachpuff peru linen bisque darkorange burlywood antiquewhite tan navajowhite blanchedalmond papayawhip moccasin orange wheat oldlace top Spectral coolwarm center baseline bottom bwr seismic Performance tips right Qualitative colormaps Text parameters API Pastel1 ax.text(…, family=…, size=…, weight=…) ax.text(…, fontproperties=…) The quick brown fox The quick brown fox The quick brown fox The quick brown fox The quick brown fox The quick brown fox The quick brown fox The quick brown fox jumps over the lazy dog The quick brown fox jumps over the lazy dog The quick brown fox jumps over the lazy dog The quick brown fox jumps over the lazy dog The quick brown fox jumps over the lazy dog large medium small x-small xx-small black bold semibold normal ultralight (900) (700) (600) (400) (100) italic normal The quick brown fox jumps over the lazy dog bar, fraction=-0.3 bar, angle=180, fraction=-0.2 Set1 small-caps normal Set2 Set3 hermite kaiser quadric tab10 tab20 tab20b Annotation arrow styles API - <- -> <-> <|- -|> <|-|> ]- -[ ]-[ |-| ]-> <-[ simple fancy wedge tab20c catrom Miscellaneous colormaps gaussian bessel terrain ocean cubehelix rainbow twilight scatter(X, Y) plot(X, Y, marker=”o”, ls=””) slow fast for i in range(n): plot(X[i]) plot(sum([x+[None] for x in X],[])) slow fast cla(), imshow(…), canvas.draw() im.set_data(…), canvas.draw() slow fast Beyond Matplotlib Dark2 (1.20) (1.00) (0.83) (0.69) (0.58) The quick brown fox jumps over the lazy dog The quick brown fox jumps over the lazy dog The quick brown fox jumps over the lazy dog bar, fraction=0.3 Accent x-large (1.44) The quick brown fox jumps over the lazy dog The quick brown fox jumps over the lazy dog hamming Paired monospace serif sans cursive The quick brown fox jumps over the lazy dog hanning Pastel2 xx-large (1.73) The quick brown fox jumps over the lazy dog spline36 … resize a figure? → fig.set_size_inches(w, h) … save a figure? → fig.savefig(”figure.pdf”) … save a transparent figure? → fig.savefig(”figure.pdf”, transparent=True) … clear a figure/an axes? → fig.clear() → ax.clear() … close all figures? → plt.close(”all”) … remove ticks? → ax.set_[xy]ticks([]) … remove tick labels ? → ax.set_[xy]ticklabels([]) … rotate tick labels ? → ax.set_[xy]ticks(rotation=90) … hide top spine? → ax.spines[’top’].set_visible(False) … hide legend border? → ax.legend(frameon=False) … show error as shaded region? → ax.fill_between(X, Y+error, Y‐error) … draw a rectangle? → ax.add_patch(plt.Rectangle((0, 0), 1, 1) … draw a vertical line? → ax.axvline(x=0.5) … draw outside frame? → ax.plot(…, clip_on=False) … use transparency? → ax.plot(…, alpha=0.25) … convert an RGB image into a gray image? → gray = 0.2989*R + 0.5870*G + 0.1140*B … set figure background color? → fig.patch.set_facecolor(“grey”) … get a reversed colormap? → plt.get_cmap(“viridis_r”) … get a discrete colormap? → plt.get_cmap(“viridis”, 10) … show a figure for one second? → fig.show(block=False), time.sleep(1) mitchell sinc lanczos Seaborn: Statistical Data Visualization Cartopy: Geospatial Data Processing yt: Volumetric data Visualization mpld3: Bringing Matplotlib to the browser Datashader: Large data processing pipeline plotnine: A Grammar of Graphics for Python Matplotlib Cheatsheets Copyright (c) 2021 Matplotlib Development Team Released under a CC‐BY 4.0 International License