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 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 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() 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 ticker.FixedLocator([0, 1, 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 ticker.MaxNLocator(n=4) 0.0 3.75 3 1.5 4.25 4.75 4 5 3.0 Styles 4.5 104 105 107 106 108 API viridis magma plasma API Greys YlOrBr Wistia API API API Spectral coolwarm RdGy tab10 tab20 twilight API plt.style.use(style) ticker.LogLocator(base=10, numticks=15) 103 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 ticker.NullLocator() 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 Animation import matplotlib.animation as mpla 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 API Matplotlib center 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 RdBu ax.text( …, ha=… , va=…, …) (1,1) 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 RdYlBu RdYlGn 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 black (900) bold (700) semibold (600) normal (400) ultralight (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 large (1.20) medium (1.00) small (0.83) x-small (0.69) xx-small (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.tick_params(axis=”x”, 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 Matplotlib for beginners Matplotlib is a library for making 2D plots in Python. It is designed with the philosophy that you should be able to create simple plots with just a few commands: 1 Initialize ax.pie(Z) Z = np.random.normal(0, 1, 100) 2 Prepare X = np.linspace(0, 4*np.pi, 1000) Y = np.sin(X) 3 Render fig, ax = plt.subplots() ax.plot(X, Y) fig.show() X = np.linspace(0, 10, 100) Y1, Y2 = np.sin(X), np.cos(X) ax.plot(X, Y1, X, Y2) ax.hist(Z) fig, (ax1, ax2) = plt.subplots(2,1) ax1.plot(X, Y1, color=”C1”) ax2.plot(X, Y2, color=”C0”) X = np.arange(5) Y = np.random.uniform(0, 1, 5) ax.errorbar(X, Y, Y∕4) fig, (ax1, ax2) = plt.subplots(1,2) ax1.plot(Y1, X, color=”C1”) ax2.plot(Y2, X, color=”C0”) Z = np.random.normal(0, 1, (100,3)) ax.boxplot(Z) 4 Observe 0 ax.contourf(Z) Z = np.random.uniform(0, 1, 4) import numpy as np import matplotlib.pyplot as plt 1.0 0.5 0.0 0.5 1.0 Organize 765 You can plot several data on the the same figure, but you 432 can also split a figure in several subplots (named Axes): 1 765 1234567 765 432 432 1 1 71 1234567 1234567 61 51 41 31 21 111 765 1234567 432 1 765 1234567 Label (everything) 432 1 A Sine wave 246 543 Tweak 21 You can modify pretty much anything in a plot, including lim1234567 its, colors, markers, line width and styles, ticks and ticks laZ = np.random.uniform(0, 1, (8,8)) ax.plot(X, Y) fig.suptitle(None) ax.set_title(”A Sine wave”) 5 10 15 20 25 30 Choose Matplotlib offers several kind of plots (see Gallery): X = np.random.uniform(0, 1, 100) Y = np.random.uniform(0, 1, 100) ax.scatter(X, Y) X = np.arange(10) Y = np.random.uniform(1, 10, 10) ax.bar(X, Y) Z = np.random.uniform(0, 1, (8,8)) ax.imshow(Z) 765 432 1 765 1234567 432 1 765 1234567 432 1 1234567 bels, titles, etc. X = np.linspace(0, 10, 100) Y = np.sin(X) ax.plot(X, Y, color=”black”) X = np.linspace(0, 10, 100) Y = np.sin(X) ax.plot(X, Y, linestyle=”--”) X = np.linspace(0, 10, 100) Y = np.sin(X) ax.plot(X, Y, linewidth=5) X = np.linspace(0, 10, 100) Y = np.sin(X) ax.plot(X, Y, marker=”o”) ax.plot(X, Y) ax.set_ylabel(None) ax.set_xlabel(”Time”) 765 Explore 432 1 Figures are shown with a graphical user interface that alto zoom and pan the figure, to navigate between the 765 1234567 lows different views and to show the value under the mouse. 432 1 765 1234567 Save (bitmap or vector format) 432 1 765 1234567 432 1 1234567 Time fig.savefig(”my-first-figure.png”, dpi=300) fig.savefig(”my-first-figure.pdf”) Matplotlib 3.5.0 handout for beginners. Copyright (c) 2021 Matplotlib Development Team. Released under a CC-BY 4.0 International License. Supported by NumFOCUS. Matplotlib for intermediate users Ticks & labels Legend from mpl.ticker import MultipleLocator as ML from mpl.ticker import ScalarFormatter as SF ax.xaxis.set_minor_locator(ML(0.2)) ax.xaxis.set_minor_formatter(SF()) ax.tick_params(axis=’x’,which=’minor’,rotation=90) ax.plot(X, np.sin(X), ”C0”, label=”Sine”) ax.plot(X, np.cos(X), ”C1”, label=”Cosine”) ax.legend(bbox_to_anchor=(0,1,1,.1),ncol=2, mode=”expand”, loc=”lower left”) Anatomy of a figure Blue signal Red signal Legend 2 3 4 4.2 4.4 4.6 4.8 1 3.2 3.4 3.6 3.8 0 Minor tick Sine and Cosine Sine 2.2 2.4 2.6 2.8 Title Major tick 1.2 1.4 1.6 1.8 4 0.2 0.4 0.6 0.8 A matplotlib figure is composed of a hierarchy of elements that forms the actual figure. Each element can be modified. Cosine 5 3 Major tick label Lines & markers Grid Y axis label Line (line plot) X = np.linspace(0.1, 10*np.pi, 1000) Y = np.sin(X) ax.plot(X, Y, ”C1o:”, markevery=25, mec=”1.0”) 2 Y axis label Markers (scatter plot) 1 1 0 1 0 Figure 0 Axes Line (line plot) fig, axs = plt.subplots(3,3) axs[0,0].set_facecolor(”#ddddff”) axs[2,2].set_facecolor(”#ffffdd”) gs = fig.add_gridspec(3, 3) ax = fig.add_subplot(gs[0, :]) ax.set_facecolor(”#ddddff”) fig, ax = plt.subplots() ax.spines[”top”].set_color(”None”) ax.spines[”right”].set_color(”None”) 10 15 20 25 30 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 Figure, axes & spines 5 fig, ax = plt.subplots() ax.set_xscale(”log”) ax.plot(X, Y, ”C1o-”, markevery=25, mec=”1.0”) 1 0 1 101 100 10 15 20 25 10 15 20 25 30 Colors color can be used, but Matplotlib offers sets of colors: 1 Any C0 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 0 2 4 6 8 10 12 14 16 0 0 2 4 6 8 10 12 14 16 fig = plt.figure(figsize=(3.15,3.15), dpi=50) plt.savefig(”figure.pdf”, dpi=600) Period 5 A 5 Consider a square figure to be included in a two-columns A4 paper with 2cm margins on each side and a column separation of 1cm. The width of a figure is (21 - 2*2 - 1)/2 = 8cm. One inch being 2.54cm, figure size should be 3.15×3.15 in. ax.fill_betweenx([-1,1],[0],[2*np.pi]) ax.text(0, -1, r” Period $\Phi$”) 0 1 0 1 Size & DPI Text & ornaments 1 0 1 ax.annotate(”A”, (X[250],Y[250]),(X[250],-1), ha=”center”, va=”center”,arrowprops = {”arrowstyle” : ”->”, ”color”: ”C1”}) 0 Scales & projections 10 1 Annotation 30 Matplotlib 3.5.0 handout for intermediate users. Copyright (c) 2021 Matplotlib Development Team. Released under a CC-BY 4.0 International License. Supported by NumFOCUS. Matplotlib tips & tricks Transparency Text outline Scatter plots can be enhanced by using transparency (al- Use text outline to make text more visible. pha) in order to show area with higher density. Multiple scatimport matplotlib.patheffects as fx ter plots can be used to delineate a frontier. text = ax.text(0.5, 0.1, ”Label”) X = np.random.normal(-1, 1, 500) Y = np.random.normal(-1, 1, 500) 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) Rasterization If your figure has many graphical elements, such as a huge scatter, you can rasterize them to save memory and keep other elements in vector format. text.set_path_effects([ fx.Stroke(linewidth=3, foreground=’1.0’), fx.Normal()]) Use the Agg backend to render a figure directly in an array. from matplotlib.backends.backend_agg import FigureCanvas canvas = FigureCanvas(Figure())) ... # draw some stuff canvas.draw() Z = np.array(canvas.renderer.buffer_rgba()) You can adjust a colorbar’s size when adding it. im = ax.imshow(Z) cb = plt.colorbar(im, fraction=0.046, pad=0.04) cb.set_ticks([]) 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 to save space on tick labels. X,Y = [], [] for x in np.linspace(0, 10*np.pi, 100): X.extend([x, x, None]), Y.extend([0, sin(x), None]) ax.plot(X, Y, ”black”) for tick in ax.get_xticklabels(which=’both’): tick.set_fontname(”Roboto Condensed”) X = np.random.normal(-1, 1, 10_000) Y = np.random.normal(-1, 1, 10_000) ax.scatter(X, Y, rasterized=True) fig.savefig(”rasterized-figure.pdf”, dpi=600) Offline rendering Colorbar adjustment Getting rid of margins Dotted lines Once your figure is finished, you can call tight_layout() to remove white margins. If there are remaining margins, you can use the pdfcrop utility (comes with TeX live). To have rounded dotted lines, use a custom linestyle and modify dash_capstyle. Hatching ax.plot([0,1], [0,0], ”C1”, linestyle = (0, (0.01, 1)), dash_capstyle=”round”) ax.plot([0,1], [1,1], ”C1”, linestyle = (0, (0.01, 2)), dash_capstyle=”round”) You can achieve a nice visual effect with thick hatch patterns. cmap = plt.get_cmap(”Oranges”) plt.rcParams[’hatch.color’] = cmap(0.2) plt.rcParams[’hatch.linewidth’] = 8 ax.bar(X, Y, color=cmap(0.6), hatch=”∕” ) 38% 27% 2018 Range of continuous colors Combining axes You can use colormap to pick from a range of continuous You can use overlaid axes with different projections. colors. X = np.random.randn(1000, 4) cmap = plt.get_cmap(”Oranges”) colors = cmap([0.2, 0.4, 0.6, 0.8]) ax.hist(X, 2, histtype=’bar’, color=colors) ax1 = fig.add_axes([0,0,1,1], label=”cartesian”) ax2 = fig.add_axes([0,0,1,1], label=”polar”, projection=”polar”) 59% 53% 2019 Read the documentation Matplotlib comes with an extensive documentation explaining the details of each command and is generally accompanied by examples. Together with the huge online gallery, this documentation is a gold-mine. Matplotlib 3.5.0 handout for tips & tricks. Copyright (c) 2021 Matplotlib Development Team. Released under a CC-BY 4.0 International License. Supported by NumFOCUS.