import matplotlib.pyplot as plt★The one import you always write.import numpy as npData almost always comes in as arrays.fig, ax = plt.subplots()★start hereOne Figure + one Axes. The modern default entry point.fig, ax = plt.subplots(figsize=(8,5))★Size in inches (width, height).fig, axs = plt.subplots(2, 3)★A 2×3 grid —axsis a NumPy array.fig, axs = plt.subplots(2, 2, layout='constrained')Auto-spaces subplots so nothing overlaps.plt.plot(x, y)Quick pyplot form — auto-creates fig + axes for you.
ax.plot(x, y)★Line plot — the workhorse.ax.plot(x, y, 'o-')★Fmt string: circles joined by a line. See card 16.ax.scatter(x, y, s=20, c=z)★Points;s=size,c=color-by-value.ax.bar(x, h)★Vertical bars;ax.barh()for horizontal.ax.fill_between(x, y1, y2)★Shade a band — great for confidence intervals.ax.stackplot(x, y1, y2)Stacked areas that sum together.ax.stem(x, y)Lollipop stems from a baseline.ax.stairs(vals, edges)Step / histogram-outline curve.
ax.hist(x, bins=30)★Histogram;density=Trueto normalize.ax.boxplot(data)★Quartiles + whiskers + outliers.ax.violinplot(data)Box plot + a mirrored density shape.ax.errorbar(x, y, yerr=e)★Points/line with error bars.ax.hexbin(x, y)2-D density as hex tiles (for dense scatter).ax.pie(sizes, labels=lbls)Pie chart — use sparingly.ax.ecdf(x)Empirical cumulative distribution.
ax.imshow(Z)★Show a matrix/image as a heatmap.ax.pcolormesh(X, Y, Z)★Colored grid on real X/Y coords (fast).ax.contour(X, Y, Z)★Iso-lines;contourffills between them.ax.quiver(X, Y, U, V)Arrows for a vector field.ax.streamplot(X, Y, U, V)Flow streamlines of a field.ax.tricontourf(x, y, z)Contours on unstructured (scattered) points.
ax.set_title("...")★Title above this Axes.ax.set_xlabel("...")★x-axis label;set_ylabelfor y.ax.set(xlabel="t", ylabel="v", title="...")★Set many properties in one call.ax.legend()★Needslabel=on each plot call first.fig.suptitle("...")One title over the whole Figure.ax.annotate("peak", xy=p, xytext=t, arrowprops={...})Text with an arrow pointing at a datapoint.ax.text(x, y, "note")Free text at data coordinates.
ax.set_xlim(0, 10)★View range;set_ylimfor y.ax.set_xticks([0,5,10])★Where ticks sit; add a 2nd list for labels.ax.tick_params(axis='x', rotation=45)Rotate / resize tick labels.ax.set_xscale('log')★Also'symlog','logit'.ax.grid(True)★Toggle the grid;which='both'incl. minor.ax.axhline(0) · ax.axvline(x)Full-width reference lines.ax.invert_yaxis()Flip an axis direction.ax.xaxis.set_major_locator(MultipleLocator(5))Fine tick control via Locators / Formatters.
ax.plot(..., color='C0')★'C0'…'C9'= the default color cycle.linewidth=2 · linestyle='--'★Aliaseslw/ls. Styles:- -- -. :marker='o' · markersize=8★Markers:o s ^ v . * + x Dalpha=0.5Transparency, 0 (clear) → 1 (solid).label="series A"★Feedsax.legend().zorder=3Higher = drawn on top.# color forms: 'red' 'r' '#1f77b4' (.2,.4,.6) '0.5'Name, 1-letter, hex, RGB tuple, or gray level.
ax.imshow(Z, cmap='viridis')★Perceptually uniform, colorblind-safe default.# sequential viridis plasma magma cividisLow→high ordered data.# diverging coolwarm RdBu bwrData with a meaningful center (0).# qualitative tab10 Set2 Pastel1Unordered categories.fig.colorbar(im, ax=ax)★The key relating color back to value.vmin=0, vmax=1Clamp the value→color range.norm=LogNorm()Non-linear mapping (e.g. log). Append_rto reverse any cmap.matplotlib.colormaps['viridis']Get a colormap object by name.cm.get_cmap®ister_cmapwere removed — usematplotlib.colormaps[...]andmatplotlib.colormaps.register(...).
fig, axs = plt.subplots(2, 3)★Regular grid → indexaxs[row, col].plt.subplots(..., layout='constrained')★Modern auto-spacing. Prefer overtight_layout().fig.subplot_mosaic("AB;CC")★Named, uneven layouts by ASCII art → dict of axes.plt.subplots(..., sharex=True)Share axis range/ticks across panels.ax2 = ax.twinx()Second y-axis sharing the same x.iax = ax.inset_axes([.6,.6,.35,.35])A small plot inside the plot.fig.add_gridspec(3, 3)Full manual control of a grid.
plt.show()★Render window / inline. Call once, at the end.fig.savefig("f.png", dpi=300)★Raster export; bumpdpifor print quality.fig.savefig("f.pdf", bbox_inches='tight')★Vector (pdf/svg);tighttrims whitespace.fig.savefig("f.svg", transparent=True)No background — good for slides.plt.close(fig)Free the figure's memory (batch jobs!).
plt.style.use('ggplot')★Instant theme. Try'bmh','fivethirtyeight'.plt.style.availableList every built-in style.with plt.style.context('dark_background'):Apply a style to just one block.plt.rcParams['font.size'] = 12★Change any default globally.plt.rcParams['figure.dpi'] = 120Sharper on-screen figures.plt.rcParams.update({...})Set several defaults at once.
ax = fig.add_subplot(projection='3d')★Opt into a 3-D Axes.ax.plot_surface(X, Y, Z)A 3-D surface; alsoscatter(x,y,z).fig.add_subplot(projection='polar')Radial / angular plots.ax.set_aspect('equal')Equal x/y scale — circles stay round.from matplotlib.animation import FuncAnimationFrame-by-frame animation →.save("a.gif").
df.plot(ax=ax)★pandas plots straight onto your Axes.df.plot(kind='bar', ax=ax)line bar barh hist box area scatter.df.plot.scatter(x='a', y='b', ax=ax)Method form of the same thing.# then keep tuning with ax.set_*()Always passax=so you stay in control.
# explicit / OO (recommended)preferYou holdfig/axand call methods on them.fig, ax = plt.subplots(); ax.plot(x,y); ax.set_title(...)Clear, scales to complex/multi-panel figures.# implicit / pyplot (state-machine)pyplot tracks a "current" Axes for you.plt.plot(x,y); plt.title(...)Fewer keystrokes; fine for quick throwaway plots.plt.plot() ≡ plt.gca().plot()pyplot is a thin wrapper:plt.title↔ax.set_title.
Axes ≠ AxisconfusingAxes = the whole plot; Axis = one x or y line.ax.legend()shows nothingYou forgotlabel=on the plot calls.from pylab import *deprecatedStrongly discouraged — pollutes the namespace.axs[0]vsaxs[0][1]subplots(2,3)gives a 2-D array — index both.- too many open figuresLoops leak memory —
plt.close(fig)each time. plt.show()thensavefig= blankshow()can clear the figure; save first.imshoworigin is top-leftRow 0 is at the top; useorigin='lower'to flip.
'ro--'red o-markers, -- dashed line.'k.:'k black, . point markers, : dotted.# line - solid -- dash -. dashdot : dotThe 4 line styles.# marker o s ^ v < > . * + x D pCommon marker glyphs.# color b g r c m y k w1-letter colors (blue…white).'C0'..'C9'The property-cycle colors, in order.'#1f77b4' (0.1,0.2,0.5) 'tab:blue' '0.5'Hex · RGB tuple · tableau name · gray level.