Matplotlib
Matplotlib draws static charts (PNG, SVG, PDF) with full control of every element. Seaborn and DataFrame.plot are built on it, so the same fig and ax methods fine-tune their charts too. This page covers the object-oriented API, layouts, plot types, text, styling and saving. Examples use data/sales.csv and data/customers.csv.
Quick lookup
Section titled “Quick lookup”| I want to… | Use… | Example |
|---|---|---|
| start a chart | plt.subplots() |
fig, ax = plt.subplots(figsize=(7, 4)) |
| a grid of charts | plt.subplots(r, c) |
fig, axs = plt.subplots(2, 2, sharex=True, layout="constrained") |
| an uneven layout | plt.subplot_mosaic |
fig, axd = plt.subplot_mosaic([["a", "a"], ["b", "c"]]) |
| loop over a grid | axs.flat |
for ax in axs.flat: ax.grid(alpha=0.3) |
| a line | ax.plot |
ax.plot(x, y, marker="o", label="2024") |
| points | ax.scatter |
ax.scatter(x, y, s=10, alpha=0.3, c=z, cmap="viridis") |
| bars | ax.bar, ax.barh |
ax.barh(names, values) |
| grouped bars | ax.grouped_bar (3.11, provisional) |
ax.grouped_bar(df, tick_labels=df.index) |
| stacked bars | bottom= |
ax.bar(x, b, bottom=a) |
| a histogram | ax.hist |
ax.hist(v, bins=30, density=True) |
| box plots | ax.boxplot |
ax.boxplot(groups, tick_labels=names) |
| an ECDF | ax.ecdf |
ax.ecdf(v) |
| a band around a line | ax.fill_between |
ax.fill_between(x, lo, hi, alpha=0.2) |
| a matrix as colors | ax.imshow + fig.colorbar |
fig.colorbar(ax.imshow(m, cmap="viridis"), ax=ax) |
| title and labels at once | ax.set |
ax.set(title="...", xlabel="...", ylabel="...", ylim=(0, None)) |
| one title for a grid | fig.suptitle, fig.supxlabel |
fig.suptitle("Q4 review") |
| a legend | ax.legend |
ax.legend(title="Channel", frameon=False, ncols=2) |
| a legend outside the plot | bbox_to_anchor |
ax.legend(loc="upper left", bbox_to_anchor=(1, 1)) |
| custom tick labels | ax.set_xticks(pos, labels=...) |
ax.set_xticks(range(1, 13), labels=calendar.month_abbr[1:]) |
120k on the axis |
FuncFormatter |
ax.yaxis.set_major_formatter(FuncFormatter(lambda v, p: f"{v/1e3:.0f}k")) |
| a percent axis | PercentFormatter |
PercentFormatter(xmax=1) for rates 0–1 |
| short date labels | ConciseDateFormatter |
mdates.ConciseDateFormatter(ax.xaxis.get_major_locator()) |
| a log axis | ax.set_yscale("log") |
or ax.semilogy(...) |
| values on bars | ax.bar_label |
ax.bar_label(bars, fmt="{:,.0f}") |
| a reference line | ax.axhline, ax.axvline, ax.axline |
ax.axhline(mean, linestyle=":") |
| shade a range | ax.axvspan, ax.axhspan |
ax.axvspan(10.5, 12.5, alpha=0.15) |
| an arrow with text | ax.annotate |
ax.annotate("peak", xy=(x, y), xytext=(tx, ty), arrowprops={"arrowstyle": "->"}) |
| text at a data point | ax.text |
ax.text(x, y, "label", ha="center") |
| hide the top and right frame | ax.spines |
ax.spines[["top", "right"]].set_visible(False) |
| a style for one chart | plt.style.context |
with plt.style.context("petroff10"): ... |
| change one default | plt.rcParams, plt.rc_context |
plt.rcParams["font.size"] = 11 |
| a colormap object | matplotlib.colormaps |
matplotlib.colormaps["viridis"] |
| a quick chart from pandas | df.plot, s.plot.barh |
df.plot(x="month", y=["a", "b"], ax=ax) |
| save a file | fig.savefig |
fig.savefig("output/chart.png", dpi=200, bbox_inches="tight") |
| free memory in a loop | plt.close(fig) |
plt.close("all") closes every figure |
Figure, Axes and the two interfaces
Section titled “Figure, Axes and the two interfaces”| Object | What it is | Get it with |
|---|---|---|
Figure |
the whole image: size, background, saving | fig, ax = plt.subplots(), ax.figure, plt.gcf() |
Axes |
one plot area with its own x and y axes | ax, axs[r, c], axd["name"], fig.axes, plt.gca() |
Axis |
the x or y axis: ticks, labels, formatters | ax.xaxis, ax.yaxis |
Artist |
anything drawn: lines, bars, text | returned by ax.plot, ax.bar; also ax.lines, ax.patches, ax.texts |
pyplot (plt.plot) draws on the current Axes; the object-oriented API (ax.plot) names the Axes. Use the object-oriented API in scripts, functions and grids.
| pyplot | Object-oriented |
|---|---|
plt.plot, plt.bar, plt.hist, plt.scatter |
ax.plot, ax.bar, ax.hist, ax.scatter |
plt.title, plt.xlabel, plt.ylabel |
ax.set_title, ax.set_xlabel, ax.set_ylabel (or one ax.set(...)) |
plt.xlim, plt.ylim, plt.xticks, plt.yticks |
ax.set_xlim, ax.set_ylim, ax.set_xticks, ax.set_yticks |
plt.legend, plt.grid, plt.text |
ax.legend, ax.grid, ax.text |
plt.savefig |
fig.savefig |
import matplotlib.pyplot as plt
fig, ax = plt.subplots() # one Axes, not an arrayfig2, axs = plt.subplots(2, 3) # a 2-D NumPy array of Axesprint(type(ax).__name__, axs.shape, axs[1, 2] is axs.flat[5])fig3, row = plt.subplots(1, 3) # one row: a 1-D array, so row[1], not row[0, 1]print(row.shape, ax.figure is fig, len(fig2.axes))plt.close("all") # close figures you do not showAxes (2, 3) True(3,) True 6Layouts
Section titled “Layouts”| Option | Effect |
|---|---|
figsize=(7, 4) |
size in inches; pixels = inches × dpi |
layout="constrained" |
no overlapping labels, titles or colorbars; prefer it to fig.tight_layout() |
sharex=True, sharey="row" |
same limits on all panels (or per row/column) |
width_ratios=[3, 1], height_ratios=[2, 1] |
uneven column widths or row heights |
squeeze=False |
always a 2-D array, even for subplots(1, 3) |
plt.subplot_mosaic([["a", "a"], ["b", "c"]]) |
named panels; "." leaves a gap; returns a dict |
fig.subfigures(1, 2) |
independent groups of panels, each with its own suptitle |
ax.twinx() |
a second y-axis on the right; two scales on one chart often mislead |
ax.inset_axes([0.6, 0.6, 0.35, 0.35]) |
a small chart inside an Axes (fractions of the Axes) |
ax.set_axis_off() |
hide an unused panel in a grid |
import pandas as pd
sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])monthly = sales.resample("MS", on="order_date")["revenue"].sum() / 1000by_cat = sales.groupby("category")["revenue"].sum().sort_values() / 1000
fig, axd = plt.subplot_mosaic([["trend", "trend"], ["cat", "hist"]], figsize=(8, 5.5), layout="constrained")axd["trend"].plot(monthly.index, monthly.to_numpy(), marker="o")axd["trend"].set(title="Monthly revenue (k USD)", ylim=(0, None))axd["cat"].barh(by_cat.index, by_cat.to_numpy()) # sorted: largest on topaxd["cat"].set(title="Revenue by category (k USD)")axd["hist"].hist(sales["revenue"], bins=40, log=True) # log counts: long tailaxd["hist"].set(title="Order line revenue (USD)", ylabel="lines (log)")print(sorted(axd), f"{monthly.max():.0f}k in {monthly.idxmax():%b %Y}")plt.show()['cat', 'hist', 'trend'] 303k in Dec 2024
Plot types
Section titled “Plot types”| Method | Chart | Key options |
|---|---|---|
ax.plot(x, y) |
line | marker="o", linestyle="--", linewidth=2, color="C1", label= |
ax.step(x, y, where="mid"), ax.stairs(h, edges) |
step line | for counts per bin or piecewise values |
ax.scatter(x, y) |
points | s= size, c= values + cmap=, alpha=, marker= |
ax.bar(x, h), ax.barh(y, w) |
bars | width=0.8, bottom= (stack), yerr=, capsize=4, color= |
ax.grouped_bar(heights, tick_labels=...) |
grouped bars (3.11+) | a DataFrame (index = groups, columns = series), a dict or a list |
ax.hist(v, bins=30) |
histogram | bins= int or edges, density=True, histtype="step", log=True |
ax.boxplot(groups) |
box plot | tick_labels=, orientation="horizontal", showfliers=False |
ax.violinplot(groups) |
violin | showmedians=True, orientation=, side="low" |
ax.ecdf(v) |
cumulative distribution | complementary=True |
ax.errorbar(x, y, yerr=e) |
points with error bars | fmt="o", capsize=4 |
ax.fill_between(x, lo, hi) |
band, area | alpha=0.2, where= |
ax.stackplot(x, ys, labels=...) |
stacked area | parts of a whole over time |
ax.pie(v, labels=...) |
pie | autopct="%1.0f%%"; prefer sorted bars |
ax.hexbin(x, y, gridsize=30) |
2-D density | mincnt=1, cmap= |
ax.imshow(m), ax.pcolormesh(X, Y, Z) |
matrix, grid | cmap=, vmin=, vmax=, aspect="auto" |
ax.contour(X, Y, Z), ax.contourf(...) |
contour lines, filled | levels=10 |
ax.axline((x0, y0), slope=m) |
infinite straight line | for y = x reference lines |
DataFrame.plot calls these methods for you: df.plot(kind=...) with "line", "bar", "barh", "hist", "box", "kde", "area", "pie", "scatter", "hexbin". It returns an Axes, so pass ax=ax to draw into a grid and finish with the ax methods below.
Labels, legends and annotations
Section titled “Labels, legends and annotations”| Task | Code |
|---|---|
| title, labels, limits | ax.set(title="...", xlabel="...", ylabel="...", xlim=(0, 10), ylim=(0, None)) |
| bold left-aligned title | ax.set_title("...", loc="left", fontweight="bold") |
| legend | ax.legend(title="Year", loc="upper left", frameon=False, ncols=2) |
| legend for a whole figure | fig.legend(loc="outside right upper") (needs layout="constrained") |
| no legend entry | label="_nolegend_" or no label= |
| rotate tick labels | ax.tick_params(axis="x", labelrotation=45) |
| fewer ticks | ax.xaxis.set_major_locator(MaxNLocator(5)) |
| one tick per month | ax.xaxis.set_major_locator(mdates.MonthLocator()) |
| grid behind the data | ax.grid(axis="y", alpha=0.3); ax.set_axisbelow(True) |
| reverse an axis | ax.invert_yaxis() (top-to-bottom bar ranking) |
| margins | ax.margins(x=0) (no gap at the ends of a line) |
| text in Axes coordinates | ax.text(0.02, 0.95, "n = 5,000", transform=ax.transAxes) |
| math in labels | ax.set_xlabel(r"$\sigma$ (mm/s)") |
Tick formatters
Section titled “Tick formatters”| Formatter | Shows | Set with |
|---|---|---|
FuncFormatter(lambda v, pos: ...) |
anything you compute | ax.yaxis.set_major_formatter(...) |
StrMethodFormatter("{x:,.0f}") |
a format string; the field is always x |
ax.yaxis.set_major_formatter("{x:,.0f}") (a string works too) |
PercentFormatter(xmax=1, decimals=0) |
25% for 0.25 |
xmax=100 (default) for values already in percent |
EngFormatter(unit="B") |
SI prefixes: 1.5 kB, 2 MB |
|
mdates.DateFormatter("%b %Y") |
dates with a strftime pattern | ax.xaxis.set_major_formatter(...) |
mdates.ConciseDateFormatter(locator) |
short dates, the year once | pair with mdates.AutoDateLocator() |
from matplotlib.ticker import EngFormatter, FuncFormatter, StrMethodFormatter
k = FuncFormatter(lambda v, pos: f"{v / 1000:,.0f}k")comma = StrMethodFormatter("{x:,.0f}")eng = EngFormatter(places=1)for value in [950, 241_098, 1_808_108]: # call a formatter as f(value, pos) print(f"{k(value, 0):>7} {comma(value, 0):>10} {eng(value, 0):>8}") 1k 950 950.0 241k 241,098 241.1 k 1,808k 1,808,108 1.8 MA finished chart
Section titled “A finished chart”import calendar
from matplotlib.ticker import FuncFormatter
y2024 = sales[sales["order_date"].dt.year == 2024]pivot = y2024.pivot_table(index=y2024["order_date"].dt.month, columns="channel", values="revenue", aggfunc="sum")fig, ax = plt.subplots(figsize=(7.5, 4), layout="constrained")for channel in pivot.columns: ax.plot(pivot.index, pivot[channel], marker="o", label=channel)ax.axvspan(10.5, 12.5, color="0.5", alpha=0.15) # shade the holiday seasonpeak = pivot["store"].idxmax()ax.annotate(f"store peak {pivot['store'].max() / 1000:.0f}k", xy=(peak, pivot["store"].max()), xytext=(8, 170_000), arrowprops={"arrowstyle": "->", "color": "0.3"})ax.set_xticks(range(1, 13), labels=calendar.month_abbr[1:])ax.yaxis.set_major_formatter(FuncFormatter(lambda v, pos: f"{v / 1000:.0f}k"))ax.set(title="2024 revenue by channel (USD)", ylim=(0, 180_000))ax.spines[["top", "right"]].set_visible(False)ax.legend(title="Channel", frameon=False)print(pivot.round(-3).astype(int).loc[[1, 11, 12]])plt.show()channel online storeorder_date1 42000 7800011 154000 11500012 147000 156000
Styles and colors
Section titled “Styles and colors”import matplotlib
print(len(plt.style.available), [s for s in plt.style.available if "petroff" in s])print(matplotlib.colormaps["viridis"].N, "colors in viridis") # registry of colormapswith plt.rc_context({"font.size": 12, "axes.spines.top": False}): # temporary print(plt.rcParams["font.size"])print(plt.rcParams["font.size"]) # back to the default28 ['petroff10', 'petroff6', 'petroff8']256 colors in viridis12.010.0| Tool | Scope | Example |
|---|---|---|
plt.style.use("petroff10") |
rest of the program | at the top of a script |
with plt.style.context("ggplot"): |
one block | one chart in a different style |
plt.rcParams["key"] = value |
rest of the program | plt.rcParams["axes.grid"] = True |
with plt.rc_context({...}): |
one block | {"font.size": 12} |
matplotlibrc file or style.mplstyle |
a project | plt.style.use("./style.mplstyle") |
| rcParams key | Example value |
|---|---|
figure.figsize, figure.dpi |
(7, 4), 100 |
savefig.dpi, savefig.bbox |
200, "tight" |
font.size, axes.titlesize, axes.titleweight |
11, "large", "bold" |
axes.spines.top, axes.spines.right |
False |
axes.grid, grid.alpha |
True, 0.3 |
axes.prop_cycle |
plt.cycler(color=["#0173b2", "#de8f05", "#029e73"]) |
| Color input | Meaning |
|---|---|
"C0" … "C9" |
the nth color of the current cycle |
"tab:blue", "steelblue" |
named colors |
"#D55E00", (0.2, 0.4, 0.6) |
hex or RGB (0–1) |
"0.7" |
a gray: "0" black, "1" white |
cmap="viridis", "cividis", "magma" |
sequential: magnitudes |
cmap="RdBu_r", "coolwarm" with vmin=-v, vmax=v |
diverging: signs, correlations |
cmap="tab10", style petroff10, tableau-colorblind10 |
qualitative, color-blind friendly |
name + "_r" |
reversed colormap |
regions = sales.pivot_table(index="region", columns="channel", values="revenue", aggfunc="sum") / 1000with plt.style.context("petroff10"): # a color-blind-friendly cycle fig, ax = plt.subplots(figsize=(7, 3.8), layout="constrained") bars = ax.grouped_bar(regions, tick_labels=regions.index, labels=regions.columns) for container in bars.bar_containers: ax.bar_label(container, fmt="{:.0f}", fontsize=8) ax.set(title="Revenue by region and channel, 2023–2024 (k USD)", ylim=(0, 650)) ax.legend(frameon=False, ncols=2)print(regions.round(0))plt.show()channel online storeregionEast 426.0 567.0North 378.0 511.0South 384.0 508.0West 332.0 491.0
Saving
Section titled “Saving”savefig option |
Effect |
|---|---|
extension .png, .svg, .pdf |
raster or vector; the format follows the name |
dpi=200 |
pixels per inch for raster: 7 × 4 in at 200 → 1400 × 800 px |
bbox_inches="tight", pad_inches=0.1 |
crop to the content; keeps labels that stick out |
transparent=True |
no background |
facecolor="white" |
a solid background (for dark themes) |
metadata={"Title": "..."} |
file metadata (PNG, PDF, SVG) |
from pathlib import Path
Path("output").mkdir(exist_ok=True)fig, ax = plt.subplots(figsize=(7, 4))ax.plot([1, 2, 3], [3, 1, 2])fig.savefig("output/line.png", dpi=200) # no bbox_inches: exact pixel sizefig.savefig("output/line.svg") # vector: sharp at any sizeprint(plt.imread("output/line.png").shape) # rows, columns, RGBAplt.close(fig) # free memory when you save in a loop(800, 1400, 4)Several charts in one PDF: from matplotlib.backends.backend_pdf import PdfPages, then with PdfPages("output/report.pdf") as pdf: pdf.savefig(fig) for each figure.
Gotchas
Section titled “Gotchas”| Trap | Symptom | Fix |
|---|---|---|
ax.title("...") |
TypeError: 'Text' object is not callable |
ax.set_title("...") or ax.set(title=...) |
plt.subplots(1, 3) then axs[0, 1] |
IndexError: too many indices |
one row gives a 1-D array: axs[1]; or squeeze=False |
ax.boxplot(..., labels=[...]) |
TypeError: ... unexpected keyword argument 'labels' in 3.11 |
tick_labels=[...] |
vert=False in boxplot or violinplot |
MatplotlibDeprecationWarning in 3.11 |
orientation="horizontal" |
matplotlib.cm.get_cmap("viridis") |
AttributeError (removed in 3.9) |
matplotlib.colormaps["viridis"] |
plt.savefig after plt.show() |
an empty image | save first, then show |
many plt.subplots in a loop |
rising memory; RuntimeWarning: More than 20 figures have been opened |
plt.close(fig) after saving |
| labels overlap in a grid | cut or overlapping titles | layout="constrained" |
plt.style.use in a library or notebook cell |
every later chart changes | with plt.style.context(...) |
| a bar chart not starting at 0 | small differences look huge | ax.set_ylim(0, None) for bars |
PercentFormatter() on rates 0–1 |
0.25 shows as 0% |
PercentFormatter(xmax=1) |
| x values not sorted | a line zigzags back and forth | sort by x first, or use ax.scatter |
ax.plot with a pandas Period index |
TypeError: float() argument must be a string or a real number, not 'Period' |
idx.to_timestamp(), or .astype(str) for labels |
jet or rainbow colormap |
false edges; not color-blind safe | viridis, cividis, or a diverging map |
twinx with two unrelated scales |
readers compare heights that do not compare | two panels with sharex=True |
plt.show() on a server or in CI (MPLBACKEND=Agg) |
nothing appears; UserWarning: FigureCanvasAgg is non-interactive |
fig.savefig(...) instead of show |
Learn more
Section titled “Learn more”- Module 28 lesson: visualization and its cheat sheet
- Master cheat sheet: Seaborn for statistical charts from a DataFrame, Plotly for interactive charts