Skip to content

Matplotlib

Matplotlib is the drawing layer under most static figures in Python, and every seaborn plot is a Matplotlib figure underneath. This page uses the object-oriented interface throughout. plt.subplots() returns a Figure and one or more Axes, and every call after that is a method on the Axes it changes. The older plt.plot() style acts on whichever Axes is current, which stops being obvious once a figure has two panels.

Task Code
Figure and one Axes fig, ax = plt.subplots(figsize=(6, 4), layout="constrained")
Grid of Axes fig, axes = plt.subplots(2, 3, sharex=True)
Named panels fig, axd = plt.subplot_mosaic([["a", "b"], ["a", "c"]])
Scatter ax.scatter(x, y, s=12, color="grey", alpha=0.8)
Line ax.plot(x, y, "o-", label="up")
Bar with values bars = ax.bar(names, values) then ax.bar_label(bars)
Histogram ax.hist(values, bins=20, range=(0, 1))
Box plot ax.boxplot([a, b], tick_labels=["ctrl", "trt"])
Error bars ax.errorbar(x, means, yerr=sds, fmt="o", capsize=3)
Shaded band ax.fill_between(x, low, high, alpha=0.25)
Horizontal box plot ax.boxplot(data, orientation="horizontal")
Matrix im = ax.imshow(z, cmap="RdBu_r", vmin=-2, vmax=2)
Color bar fig.colorbar(im, ax=ax, label="z-score")
Reference lines ax.axhline(y), ax.axvline(x)
Labels and title ax.set(xlabel="x", ylabel="y", title="t")
Tick labels ax.set_xticks(pos, labels=names, rotation=45)
Log axis ax.set_yscale("log")
Text at a point ax.annotate("GENE1", (x, y), xytext=(4, 4), textcoords="offset points")
Panel letter ax.set_title("A", loc="left", fontweight="bold")
Hide spines ax.spines[["top", "right"]].set_visible(False)
Temporary style with plt.style.context("ggplot"):
Editable PDF text plt.rcParams["pdf.fonttype"] = 42
Save fig.savefig("fig.pdf", bbox_inches="tight")
Close plt.close(fig)

Every example uses the same simulated experiment, with 500 genes in 6 control and 6 treated samples on a log2 CPM scale. Sixty genes shift by 1 to 3 log2 units in the treated samples.

from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy import stats
Path("outputs").mkdir(exist_ok=True)
pd.set_option("display.width", 80)
rng = np.random.default_rng(42)
n_genes = 500
genes = [f"GENE{i:03d}" for i in range(1, n_genes + 1)]
samples = [f"ctrl_{i}" for i in range(1, 7)]
samples += [f"trt_{i}" for i in range(1, 7)]
is_treated = np.repeat([False, True], 6)
# A baseline per gene plus noise per sample, then a shift in treated.
log_cpm = rng.normal(6, 2, (n_genes, 1)) + rng.normal(0, 0.6, (n_genes, 12))
changed = rng.choice(n_genes, 60, replace=False)
shift = rng.choice([-1, 1], 60) * rng.uniform(1, 3, 60)
log_cpm[np.ix_(changed, is_treated)] += shift[:, None]
expr = pd.DataFrame(log_cpm, index=genes, columns=samples)
print(expr.iloc[:3, [0, 1, 6, 7]].round(2))
ctrl_1 ctrl_2 trt_1 trt_2
GENE001 7.43 7.15 8.06 6.87
GENE002 3.98 3.87 4.46 4.90
GENE003 8.34 7.24 7.28 6.94

A t-test per gene stands in for DESeq2 here, so the page needs nothing beyond SciPy. The result has the columns a real differential expression table has.

treated = expr.loc[:, is_treated]
control = expr.loc[:, ~is_treated]
de = pd.DataFrame({
"log2fc": treated.mean(axis=1) - control.mean(axis=1),
"pvalue": stats.ttest_ind(treated, control, axis=1).pvalue,
})
de["padj"] = stats.false_discovery_control(de["pvalue"])
de["neg_log10_padj"] = -np.log10(de["padj"])
de["direction"] = np.select(
[(de["padj"] < 0.05) & (de["log2fc"] > 1),
(de["padj"] < 0.05) & (de["log2fc"] < -1)],
["up", "down"],
default="ns",
)
colors = {"up": "#B2182B", "down": "#2166AC", "ns": "#BBBBBB"}
print(de.sort_values("padj").head().to_string(float_format="{:.3g}".format))
print(de["direction"].value_counts())
log2fc pvalue padj neg_log10_padj direction
GENE287 -2.7 2.68e-07 6.69e-05 4.17 down
GENE269 -1.78 2.65e-07 6.69e-05 4.17 down
GENE393 -2.3 7.13e-07 7.13e-05 4.15 down
GENE362 3.18 6.58e-07 7.13e-05 4.15 up
GENE226 -2.57 5.43e-07 7.13e-05 4.15 down
direction
ns 449
down 30
up 21
Name: count, dtype: int64

figsize is in inches. layout="constrained" keeps labels inside the figure and replaces the older fig.tight_layout() call. One scatter call per direction gives each group its own legend entry.

fig, ax = plt.subplots(figsize=(6, 4.5), layout="constrained")
for direction, color in colors.items():
hits = de[de["direction"] == direction]
ax.scatter(hits["log2fc"], hits["neg_log10_padj"], s=12, color=color,
alpha=0.8, label=f"{direction} ({len(hits)})")
ax.axhline(-np.log10(0.05), ls="--", lw=0.8, color="grey")
ax.axvline(-1, ls="--", lw=0.8, color="grey")
ax.axvline(1, ls="--", lw=0.8, color="grey")
ax.set(xlabel="log2 fold change", ylabel="-log10 adjusted p-value",
title="Treated vs control")
ax.legend(frameon=False)
fig.savefig("outputs/matplotlib-volcano.png", dpi=150, bbox_inches="tight")

Volcano plot of 500 simulated genes. 449 grey non-significant genes form a cloud near zero fold change and below the dashed padj line. 21 red up-regulated and 30 blue down-regulated genes sit beyond the dashed lines at log2 fold change of minus 1 and 1.

The Axes from the volcano is still open, so the labels go on top of it. xytext with textcoords="offset points" nudges each label a few points away from its marker. Pick genes that sit apart; the lowest adjusted p-values here tie at the top of the plot, and their labels would print over each other.

significant = de[de["direction"] != "ns"]
top_hits = pd.concat([significant.nlargest(3, "log2fc"),
significant.nsmallest(3, "log2fc")])
for gene, row in top_hits.iterrows():
ax.annotate(gene, (row["log2fc"], row["neg_log10_padj"]),
xytext=(4, 4), textcoords="offset points", fontsize=8)
fig.savefig("outputs/matplotlib-volcano-labels.png", dpi=150,
bbox_inches="tight")
plt.close(fig)

The same volcano plot with six genes labeled by name. GENE362, GENE257, and GENE311 are the largest up-regulated changes, near log2 fold change 3. GENE287, GENE168, and GENE230 are the largest down-regulated changes, near minus 2.7.

Close each figure with plt.close(fig) once it is saved. A script that keeps opening figures holds all of them in memory, and Matplotlib warns once more than 20 are open.

A line plot fits anything measured along an ordered axis. Here it shows how many significant genes survive as the fold-change cutoff rises.

cutoffs = np.arange(0, 3.01, 0.25)
sig = de[de["padj"] < 0.05]
n_up = [(sig["log2fc"] > cut).sum() for cut in cutoffs]
n_down = [(sig["log2fc"] < -cut).sum() for cut in cutoffs]
fig, ax = plt.subplots(figsize=(5, 3.5), layout="constrained")
ax.plot(cutoffs, n_up, "o-", color=colors["up"], label="up")
ax.plot(cutoffs, n_down, "s-", color=colors["down"], label="down")
ax.set(xlabel="|log2 fold change| cutoff", ylabel="genes with padj < 0.05")
ax.legend(frameon=False)
fig.savefig("outputs/matplotlib-line.png", dpi=150, bbox_inches="tight")
plt.close(fig)

Line plot of significant gene counts against the absolute log2 fold change cutoff. The down line holds at 30 genes up to a cutoff of 1.25 and then falls to 0 at 2.75. The up line starts at 24 and falls to 3 at a cutoff of 3.

ax.fill_between shades the area between two curves, which is how a confidence band goes around a time course. The example follows the top up-regulated gene for 24 hours after treatment, with four replicates per time point and a t-based 95% interval.

tc_gene = top_hits.index[0]
start = expr.loc[tc_gene, ~is_treated].mean()
end = expr.loc[tc_gene, is_treated].mean()
hours = np.array([0, 2, 4, 8, 12, 24])
curve = start + (end - start) * (1 - np.exp(-hours / 4))
reps = curve + rng.normal(0, 0.4, (4, hours.size))
tc_mean = reps.mean(axis=0)
ci_half = stats.t.ppf(0.975, df=3) * stats.sem(reps, axis=0)
tc_table = pd.DataFrame({"hours": hours, "mean": tc_mean,
"ci_low": tc_mean - ci_half,
"ci_high": tc_mean + ci_half})
print(tc_table.round(2).to_string(index=False))
fig, ax = plt.subplots(figsize=(5, 3.5), layout="constrained")
ax.fill_between(hours, tc_mean - ci_half, tc_mean + ci_half,
color=colors["up"], alpha=0.25, linewidth=0, label="95% CI")
ax.plot(hours, tc_mean, "o-", color=colors["up"], label="mean of 4")
ax.set(xlabel="hours after treatment", ylabel=f"{tc_gene} log2 CPM")
ax.legend(frameon=False)
fig.savefig("outputs/matplotlib-fill-between.png", dpi=150,
bbox_inches="tight")
plt.close(fig)
hours mean ci_low ci_high
0 6.34 5.23 7.44
2 7.05 6.10 8.00
4 7.88 7.65 8.11
8 8.72 8.17 9.28
12 8.79 8.15 9.44
24 9.29 8.43 10.15

Time course of GENE362 over 24 hours after treatment. The mean of four replicates rises from 6.34 log2 CPM at 0 hours to 8.72 at 8 hours and 9.29 at 24 hours. The shaded 95% band is narrowest at 4 hours, from 7.65 to 8.11, and widest at 0 and 24 hours.

ax.bar_label writes the value on each bar. It replaces the loop over ax.text calls found in older tutorials.

counts = de["direction"].value_counts().reindex(["up", "down", "ns"])
fig, ax = plt.subplots(figsize=(4, 3.5), layout="constrained")
bars = ax.bar(counts.index, counts.to_numpy(),
color=[colors[d] for d in counts.index])
ax.bar_label(bars, padding=2)
ax.set_ylabel("genes")
ax.spines[["top", "right"]].set_visible(False)
fig.savefig("outputs/matplotlib-bar.png", dpi=150, bbox_inches="tight")
plt.close(fig)

Bar chart of gene counts by direction, with the count printed above each bar. There are 21 up, 30 down, and 449 not significant.

The raw p-value histogram is the first check on any differential expression run. Null genes spread flat across the range, and real changes pile up in the first bin.

fig, ax = plt.subplots(figsize=(5, 3.5), layout="constrained")
ax.hist(de["pvalue"], bins=20, range=(0, 1), color="#4C72B0",
edgecolor="white")
ax.set(xlabel="raw p-value", ylabel="genes")
fig.savefig("outputs/matplotlib-histogram.png", dpi=150, bbox_inches="tight")
plt.close(fig)

Histogram of raw p-values in 20 bins. The first bin holds about 83 genes, and the other 19 bins form a flat floor of 14 to 32 genes each.

With six samples per group, show the points as well as the box. Matplotlib 3.9 renamed labels= to tick_labels=, and 3.11 no longer accepts the old name. vert=False is deprecated too; pass orientation="horizontal" instead.

gene = top_hits.index[0]
groups = [expr.loc[gene, ~is_treated], expr.loc[gene, is_treated]]
fig, ax = plt.subplots(figsize=(3.5, 4), layout="constrained")
ax.boxplot(groups, tick_labels=["control", "treated"], widths=0.5,
showfliers=False)
for position, values in enumerate(groups, start=1):
jitter = rng.uniform(-0.08, 0.08, len(values))
ax.scatter(position + jitter, values, s=18, color="black", zorder=3)
ax.set_ylabel(f"{gene} log2 CPM")
fig.savefig("outputs/matplotlib-boxplot.png", dpi=150, bbox_inches="tight")
plt.close(fig)

Box plot of GENE362 in control and treated samples, with the six points of each group drawn over its box. Control sits near 6 log2 CPM and treated near 9.

ax.errorbar draws a point with a whisker of any length you pass as yerr. Here it gives the mean and standard deviation per group for the six labeled genes, with the two groups nudged apart on the x axis.

condition = np.where(is_treated, "treated", "control")
sub = expr.loc[top_hits.index].T
means = sub.groupby(condition).mean()
sds = sub.groupby(condition).std()
x = np.arange(len(top_hits))
fig, ax = plt.subplots(figsize=(6, 3.8), layout="constrained")
for offset, group in [(-0.12, "control"), (0.12, "treated")]:
ax.errorbar(x + offset, means.loc[group], yerr=sds.loc[group], fmt="o",
capsize=3, label=group)
ax.set_xticks(x, labels=top_hits.index, rotation=30, ha="right")
ax.set_ylabel("log2 CPM, mean and SD")
ax.legend(frameon=False)
fig.savefig("outputs/matplotlib-errorbar.png", dpi=150, bbox_inches="tight")
plt.close(fig)

Mean and standard deviation of six genes, control in blue and treated in orange. GENE362, GENE257, and GENE311 are about 3 log2 units higher in treated, and GENE168, GENE230, and GENE287 are about 2.7 units lower.

imshow draws a matrix cell by cell. Scale each gene to a z-score first, so the color shows the pattern across samples rather than the expression level. set_xticks takes the labels directly since Matplotlib 3.5.

top_genes = de.nsmallest(20, "padj").sort_values("log2fc").index
z = expr.loc[top_genes]
z = z.sub(z.mean(axis=1), axis=0).div(z.std(axis=1), axis=0)
fig, ax = plt.subplots(figsize=(6, 5), layout="constrained")
im = ax.imshow(z, cmap="RdBu_r", vmin=-2, vmax=2, aspect="auto")
ax.set_xticks(range(z.shape[1]), labels=z.columns, rotation=45, ha="right")
ax.set_yticks(range(z.shape[0]), labels=z.index, fontsize=7)
fig.colorbar(im, ax=ax, label="row z-score")
fig.savefig("outputs/matplotlib-heatmap.png", dpi=150, bbox_inches="tight")
plt.close(fig)

Heatmap of the 20 most significant genes across 12 samples, sorted by fold change. The top 9 rows are red in the six control samples and blue in the six treated samples, and the 11 rows below show the reverse.

For clustered rows and columns, use sns.clustermap from the seaborn cheatsheet.

plt.subplot_mosaic names each panel and lets one panel span several cells. The layout is a nested list, and the same name repeated marks a span.

fig, axd = plt.subplot_mosaic(
[["volcano", "pvalues"], ["volcano", "counts"]],
figsize=(9, 5), layout="constrained", width_ratios=[1.6, 1],
)
axd["volcano"].scatter(de["log2fc"], de["neg_log10_padj"], s=8,
color=de["direction"].map(colors))
axd["volcano"].set(xlabel="log2 fold change",
ylabel="-log10 adjusted p-value")
axd["pvalues"].hist(de["pvalue"], bins=20, range=(0, 1), color="#4C72B0",
edgecolor="white")
axd["pvalues"].set(xlabel="raw p-value", ylabel="genes")
axd["counts"].bar(counts.index, counts.to_numpy(),
color=[colors[d] for d in counts.index])
axd["counts"].set_ylabel("genes")
for letter, ax in zip("ABC", axd.values()):
ax.set_title(letter, loc="left", fontweight="bold")
fig.savefig("outputs/matplotlib-mosaic.png", dpi=150, bbox_inches="tight")
plt.close(fig)

Three-panel figure. Panel A, the volcano plot, spans the left column. Panel B, the p-value histogram, and panel C, the direction bar chart, stack on the right.

For a plain grid, plt.subplots(2, 3) returns a 2 by 3 array of Axes, and sharex=True or sharey=True links their limits.

A style is a bundle of rcParams. plt.style.context applies one inside a with block, so it does not leak into later figures the way plt.style.use does. The seaborn styles are named seaborn-v0_8-* since Matplotlib 3.6, and the old "seaborn-whitegrid" name now raises an OSError.

print([s for s in plt.style.available if not s.startswith("seaborn")])
with plt.style.context("ggplot"):
fig, ax = plt.subplots(figsize=(5, 3.5), layout="constrained")
ax.hist(de["log2fc"], bins=30)
ax.set(xlabel="log2 fold change", ylabel="genes")
fig.savefig("outputs/matplotlib-style.png", dpi=150, bbox_inches="tight")
plt.close(fig)
['Solarize_Light2', 'bmh', 'classic', 'dark_background', 'fast', 'fivethirtyeight', 'ggplot', 'grayscale', 'petroff10', 'petroff6', 'petroff8', 'tableau-colorblind10']

Histogram of log2 fold changes drawn with the ggplot style, with a grey panel background, white grid lines, and red-orange bars. Most genes sit between minus 1 and 1, and small groups of bars sit near minus 2.5 and plus 2.5.

Set the defaults once at the top of a figure script. pdf.fonttype 42 embeds TrueType fonts, and svg.fonttype "none" writes text as text, so labels stay editable in Illustrator or Inkscape. A single journal column is about 3.5 inches wide.

plt.rcParams.update({
"font.size": 8,
"axes.spines.top": False,
"axes.spines.right": False,
"pdf.fonttype": 42,
"svg.fonttype": "none",
})
fig, ax = plt.subplots(figsize=(3.5, 2.6), layout="constrained")
for direction, color in colors.items():
hits = de[de["direction"] == direction]
ax.scatter(hits["log2fc"], hits["neg_log10_padj"], s=4, color=color)
ax.set(xlabel="log2 fold change", ylabel="-log10 adjusted p-value")
fig.savefig("outputs/matplotlib-journal.png", dpi=150, bbox_inches="tight")

Single-column volcano plot, 3.5 inches wide, with 8 point text and no top or right axis lines.

The file extension picks the format. dpi matters only for raster formats such as PNG; PDF and SVG stay sharp at any size. bbox_inches="tight" trims empty margins. facecolor="white" forces a white background, which matters when a style or a notebook theme has set a different figure color, and transparent=True does the opposite.

fig.savefig("outputs/matplotlib-figure.pdf", bbox_inches="tight")
fig.savefig("outputs/matplotlib-figure.svg", bbox_inches="tight")
fig.savefig("outputs/matplotlib-figure-300dpi.png", dpi=300,
bbox_inches="tight", facecolor="white")
plt.close(fig)
plt.rcdefaults()

plt.rcdefaults() restores the default settings for any figure drawn after this point.

Hunter, 2007 describes Matplotlib as a 2D graphics environment for Python.

  • Matplotlib quick start

    The guide explains Figure, Axes, plot methods, annotations, and subplot layouts. Its object-oriented examples help keep each volcano, heatmap, and mosaic operation attached to the intended panel.