Skip to content

Plotly

Plotly draws interactive figures. Hovering a point shows its values, dragging zooms, and a click on a legend entry hides that group. plotly.express, imported as px, builds a whole figure from a tidy table in one call. plotly.graph_objects, imported as go, builds it trace by trace when you need control that px does not expose.

The figures on this page are static PNG exports, so they do not respond to the mouse. In a notebook, fig.show() renders the live figure. In a script on a desktop, it opens the figure in a browser tab. On a server with no browser, write an HTML file instead, as shown in the export section.

Task Code
Scatter px.scatter(df, x="x", y="y", color="group", hover_name="gene")
Format hover values hover_data={"padj": ":.2e", "group": False}
Fixed colors color_discrete_map={"up": "#B2182B", "down": "#2166AC"}
Category order category_orders={"group": ["up", "down", "ns"]}
Box with points px.box(df, x="group", y="value", points="all")
Strip px.strip(df, x="gene", y="value", color="group")
Violin px.violin(df, x="group", y="value", box=True)
Histogram, exact bins fig.update_traces(xbins={"start": 0, "end": 1, "size": 0.05})
Bar with values px.bar(df, x="name", y="count", text_auto=True)
Heatmap px.imshow(m, color_continuous_scale="RdBu_r", color_continuous_midpoint=0)
Facets facet_col="gene", facet_col_wrap=3
Free y axes in facets fig.update_yaxes(matches=None, showticklabels=True)
Reference lines fig.add_hline(y=1.3), fig.add_vline(x=1)
Line with error bars px.line(df, x="hours", y="mean", color="gene", error_y="sd", markers=True)
OLS trend line px.scatter(df, x="x", y="y", trendline="ols", trendline_scope="overall")
Fit results px.get_trendline_results(fig).iloc[0]["px_fit_results"]
Empty figure and traces fig = go.Figure() then fig.add_trace(go.Scatter(...))
Grid of panels make_subplots(rows=1, cols=2) then add_trace(..., row=1, col=2)
3D scatter px.scatter_3d(df, x="PC1", y="PC2", z="PC3", color="group")
Axis titles fig.update_layout(xaxis_title="x", yaxis_title="y")
Hide legend fig.update_layout(showlegend=False)
Default template pio.templates.default = "simple_white"
Show fig.show()
Interactive file fig.write_html("fig.html", include_plotlyjs="cdn")
Static file fig.write_image("fig.png", width=700, height=500, scale=2)

One simulated experiment runs through the page, with 500 genes in 12 samples, 6 control and 6 treated, run in two batches. Sixty genes shift by 1 to 3 log2 units in the treated samples, and every gene carries a small batch offset of its own.

from pathlib import Path
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
import plotly.io as pio
from plotly.subplots import make_subplots
from scipy import stats
Path("outputs").mkdir(exist_ok=True)
pd.set_option("display.width", 80)
pio.templates.default = "simple_white"
rng = np.random.default_rng(42)
n_genes = 500
genes = [f"GENE{i:03d}" for i in range(1, n_genes + 1)]
samples = pd.DataFrame({
"sample": [f"S{i:02d}" for i in range(1, 13)],
"condition": np.repeat(["control", "treated"], 6),
"batch": np.tile(["b1", "b2"], 6),
})
is_treated = (samples["condition"] == "treated").to_numpy()
in_b2 = (samples["batch"] == "b2").to_numpy()
log_cpm = rng.normal(6, 2, (n_genes, 1)) + rng.normal(0, 0.6, (n_genes, 12))
log_cpm[:, in_b2] += rng.normal(0, 0.6, (n_genes, 1))
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["sample"])

A t-test per gene stands in for DESeq2. Plotly reads columns by name, so the gene names go in a column of their own rather than in the index.

treated = expr.loc[:, is_treated]
control = expr.loc[:, ~is_treated]
de = pd.DataFrame({
"gene": genes,
"log2fc": (treated.mean(axis=1) - control.mean(axis=1)).to_numpy(),
"pvalue": stats.ttest_ind(treated, control, axis=1).pvalue,
"mean_log2_cpm": expr.mean(axis=1).to_numpy(),
})
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(index=False, float_format="{:.3g}".format))
gene log2fc pvalue mean_log2_cpm padj neg_log10_padj direction
GENE151 3.41 7.67e-07 7.16 0.000128 3.89 up
GENE185 -2.78 5.43e-07 5.35 0.000128 3.89 down
GENE031 2.88 3.56e-07 11.4 0.000128 3.89 up
GENE457 2.64 5.91e-06 9.38 0.000487 3.31 up
GENE200 2.86 4.88e-06 7.2 0.000487 3.31 up

pio.templates.default = "simple_white" sets the look of every figure after it. The other built-in templates include "plotly", "plotly_white", "ggplot2", and "presentation".

hover_name puts the gene in bold at the top of the hover box. hover_data adds columns and formats them; False hides a column that px would otherwise show.

fig = px.scatter(
de, x="log2fc", y="neg_log10_padj", color="direction",
color_discrete_map=colors, hover_name="gene",
hover_data={"padj": ":.2e", "mean_log2_cpm": ":.1f", "direction": False},
category_orders={"direction": ["up", "down", "ns"]},
labels={"log2fc": "log2 fold change",
"neg_log10_padj": "-log10 adjusted p-value"},
)
fig.add_hline(y=-np.log10(0.05), line_dash="dash", line_color="grey")
fig.add_vline(x=-1, line_dash="dash", line_color="grey")
fig.add_vline(x=1, line_dash="dash", line_color="grey")
fig.write_image("outputs/plotly-volcano.png", width=700, height=500,
scale=1.5)

Volcano plot of 500 genes with 31 up-regulated genes in red, 15 down-regulated genes in blue, and 454 non-significant genes in grey. Dashed lines mark log2 fold change minus 1 and 1 and padj 0.05.

facet_col draws one panel per value of a column, and points="all" shows every sample next to its box. Facets share the y axis by default. matches=None frees it, and for_each_annotation trims the gene= prefix from each panel title.

sig = de[de["padj"] < 0.05]
top4 = sig.loc[sig["log2fc"].abs().nlargest(4).index, "gene"]
long = (
expr.loc[top4].rename_axis("gene").reset_index()
.melt(id_vars="gene", var_name="sample", value_name="log2_cpm")
.merge(samples, on="sample")
)
fig = px.box(long, x="condition", y="log2_cpm", color="condition",
facet_col="gene", points="all", hover_data=["sample", "batch"],
labels={"log2_cpm": "log2 CPM", "condition": ""})
fig.update_yaxes(matches=None, showticklabels=True)
fig.for_each_annotation(lambda a: a.update(text=a.text.split("=")[-1]))
fig.update_layout(showlegend=False)
fig.write_image("outputs/plotly-box-facets.png", width=900, height=400,
scale=1.5)

Four box plot panels for GENE151, GENE234, GENE195, and GENE162, each comparing control and treated with the six samples per condition drawn beside each box. Each panel has its own y axis, and treated sits 2.5 to 3.5 log2 units above control in all four.

facet_col_wrap=3 wraps the panels onto several rows, and facet_row splits by a second column.

px.strip draws every sample as a jittered point, with no box. The default stripmode="group" sets the colors side by side within each gene, and "overlay" stacks them in one column.

fig = px.strip(long, x="gene", y="log2_cpm", color="condition",
hover_data=["sample", "batch"],
labels={"log2_cpm": "log2 CPM", "gene": ""})
fig.write_image("outputs/plotly-strip.png", width=700, height=420,
scale=1.5)

Strip plot of GENE151, GENE234, GENE195, and GENE162, with six blue control points and six orange treated points side by side for each gene. Treated points sit about 3 log2 units above control for every gene.

A violin per sample is a quick check on the whole expression distribution before any test. box=True draws a small box inside each violin, and points=False drops the outlier markers that px.violin draws by default. violinmode="overlay" keeps each violin centered on its sample; the default "group" mode leaves room beside it for the other condition.

all_long = (expr.melt(var_name="sample", value_name="log2_cpm")
.merge(samples, on="sample"))
fig = px.violin(all_long, x="sample", y="log2_cpm", color="condition",
box=True, points=False, violinmode="overlay",
labels={"log2_cpm": "log2 CPM"})
fig.write_image("outputs/plotly-violin.png", width=900, height=400,
scale=1.5)

Twelve violins, one per sample, six blue for control and six orange for treated, each with a small box inside. All twelve have a similar shape, with a median near 6 log2 CPM and tails from about minus 2 to 15.

nbins in px.histogram is a hint, and Plotly may choose a different bin width. Set xbins on the trace to get exact bins.

fig = px.histogram(de, x="pvalue", labels={"pvalue": "raw p-value"})
fig.update_traces(xbins={"start": 0, "end": 1, "size": 0.05},
marker_line_color="white", marker_line_width=1)
fig.update_yaxes(title_text="genes")
fig.write_image("outputs/plotly-histogram.png", width=600, height=400,
scale=1.5)

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

text_auto=True prints each bar’s value on the bar.

counts = (de["direction"].value_counts()
.reindex(["up", "down", "ns"])
.rename_axis("direction")
.reset_index(name="genes"))
fig = px.bar(counts, x="direction", y="genes", color="direction",
color_discrete_map=colors, text_auto=True)
fig.update_layout(showlegend=False)
fig.write_image("outputs/plotly-bar.png", width=500, height=400, scale=1.5)

Bar chart of gene counts by direction with the count printed on each bar. There are 31 up, 15 down, and 454 not significant.

px.imshow draws a matrix and takes its row and column labels from a DataFrame’s index and columns. range_color fixes the color limits, and color_continuous_midpoint=0 centers a diverging scale.

top20 = de.nsmallest(20, "padj").sort_values("log2fc")["gene"]
z = expr.loc[top20]
z = z.sub(z.mean(axis=1), axis=0).div(z.std(axis=1), axis=0)
fig = px.imshow(z, color_continuous_scale="RdBu_r", range_color=[-2, 2],
color_continuous_midpoint=0, aspect="auto",
labels={"color": "z-score", "x": "", "y": ""})
fig.write_image("outputs/plotly-heatmap.png", width=650, height=550,
scale=1.5)

Heatmap of the 20 most significant genes across 12 samples as row z-scores, sorted by fold change. The top 5 rows are red in control samples S01 to S06 and blue in treated samples S07 to S12, and the 15 rows below show the reverse.

text_auto=".1f" prints the value in each cell. For finer control, build a go.Heatmap trace with z, x, y, and zmid=0.

px.line draws one line per value of color, in the order of x. The example follows the three most significant genes for 24 hours after treatment, three replicates per time point, and error_y adds the standard deviation at each point.

hours = np.array([0, 2, 4, 8, 12, 24])
tc_genes = de.nsmallest(3, "padj")["gene"]
tc = pd.DataFrame(
[(gene, h, rep) for gene in tc_genes for h in hours for rep in range(1, 4)],
columns=["gene", "hours", "replicate"],
)
start = tc["gene"].map(control.mean(axis=1))
end = tc["gene"].map(treated.mean(axis=1))
tc["log2_cpm"] = (start + (end - start) * (1 - np.exp(-tc["hours"] / 4))
+ rng.normal(0, 0.3, len(tc)))
tc_summary = (tc.groupby(["gene", "hours"], as_index=False)["log2_cpm"]
.agg(mean="mean", sd="std"))
fig = px.line(tc_summary, x="hours", y="mean", color="gene", error_y="sd",
markers=True,
labels={"hours": "hours after treatment",
"mean": "log2 CPM, mean and SD"})
fig.write_image("outputs/plotly-time-course.png", width=650, height=420,
scale=1.5)

Time course of three genes over 24 hours with error bars of one standard deviation. GENE031 rises from about 10.0 to 13.0 log2 CPM, GENE151 rises from about 5.5 to 8.9, and GENE185 falls from about 6.8 to 4.2.

go.Figure starts empty, and each add_trace adds one layer. A go.Scatter trace with mode="lines+markers" is a line plot.

cutoffs = np.arange(0, 3.01, 0.25)
n_up = [(sig["log2fc"] > cut).sum() for cut in cutoffs]
n_down = [(sig["log2fc"] < -cut).sum() for cut in cutoffs]
fig = go.Figure()
fig.add_trace(go.Scatter(x=cutoffs, y=n_up, mode="lines+markers", name="up",
line={"color": colors["up"]}))
fig.add_trace(go.Scatter(x=cutoffs, y=n_down, mode="lines+markers",
name="down", line={"color": colors["down"]}))
fig.update_layout(xaxis_title="|log2 fold change| cutoff",
yaxis_title="genes with padj < 0.05")
fig.write_image("outputs/plotly-line.png", width=600, height=400, scale=1.5)

Line plot of significant gene counts against the fold change cutoff. The up line falls from 32 genes at a cutoff of 0 to 4 at a cutoff of 3, and the down line falls from 17 to 0.

make_subplots sets up the grid, and row and col on add_trace place each trace. Axis titles go on with update_xaxes and update_yaxes, one panel at a time.

fig = make_subplots(rows=1, cols=2,
subplot_titles=("Volcano", "Raw p-values"))
fig.add_trace(
go.Scatter(x=de["log2fc"], y=de["neg_log10_padj"], mode="markers",
marker={"color": de["direction"].map(colors), "size": 5},
text=de["gene"], showlegend=False),
row=1, col=1,
)
fig.add_trace(
go.Histogram(x=de["pvalue"], xbins={"start": 0, "end": 1, "size": 0.05},
marker_color="#4C72B0", showlegend=False),
row=1, col=2,
)
fig.update_xaxes(title_text="log2 fold change", row=1, col=1)
fig.update_yaxes(title_text="-log10 adjusted p-value", row=1, col=1)
fig.update_xaxes(title_text="raw p-value", row=1, col=2)
fig.update_yaxes(title_text="genes", row=1, col=2)
fig.write_image("outputs/plotly-subplots.png", width=900, height=400,
scale=1.5)

Two-panel figure with the volcano plot, titled Volcano, on the left and the raw p-value histogram, titled Raw p-values, on the right.

trendline="ols" fits a least-squares line with statsmodels, which must be installed. With color set, px fits one line per color unless trendline_scope="overall". px.get_trendline_results returns the fitted statsmodels results. The example asks whether the fold changes from batch b1 agree with those from batch b2.

in_b1 = ~in_b2
fc_batch = pd.DataFrame({
"gene": genes,
"b1": (expr.loc[:, is_treated & in_b1].mean(axis=1)
- expr.loc[:, ~is_treated & in_b1].mean(axis=1)).to_numpy(),
"b2": (expr.loc[:, is_treated & in_b2].mean(axis=1)
- expr.loc[:, ~is_treated & in_b2].mean(axis=1)).to_numpy(),
"direction": de["direction"],
})
fig = px.scatter(fc_batch, x="b1", y="b2", color="direction",
color_discrete_map=colors, hover_name="gene",
category_orders={"direction": ["up", "down", "ns"]},
trendline="ols", trendline_scope="overall",
trendline_color_override="black",
labels={"b1": "log2 fold change, batch b1",
"b2": "log2 fold change, batch b2"})
fit = px.get_trendline_results(fig).iloc[0]["px_fit_results"]
print("intercept and slope:", fit.params.round(3).tolist())
print("R squared:", round(fit.rsquared, 3))
fig.write_image("outputs/plotly-trendline.png", width=650, height=500,
scale=1.5)
intercept and slope: [0.051, 0.682]
R squared: 0.48

Scatter of log2 fold change in batch b2 against batch b1 for 500 genes, colored by direction, with a black OLS line. Up-regulated genes sit at the upper right, down-regulated genes at the lower left, and non-significant genes in a cloud around zero.

The fit has a slope of 0.68, not 1, because the b1 fold changes on the x axis carry their own noise, and noise in x flattens an OLS slope. The two batches agree on the sign of the change for all 46 significant genes.

A 3D plot pays off only when the reader can rotate it, which is the case for an interactive Plotly figure. Here the first three principal components of the 12 samples come from an SVD of the gene-centered matrix. PC1 splits control from treated, and PC2 splits the batches.

centered = expr.sub(expr.mean(axis=1), axis=0).to_numpy()
_, s, vt = np.linalg.svd(centered, full_matrices=False)
pct = 100 * s**2 / (s**2).sum()
print("variance explained, %:", pct[:3].round(1).tolist())
pcs = samples.assign(PC1=vt[0] * s[0], PC2=vt[1] * s[1], PC3=vt[2] * s[2])
print(pcs.round(1).to_string(index=False))
fig = px.scatter_3d(pcs, x="PC1", y="PC2", z="PC3", color="condition",
symbol="batch", hover_name="sample",
template="plotly_white",
color_discrete_sequence=px.colors.qualitative.D3)
fig.update_traces(marker_size=6)
fig.update_layout(scene_camera={"eye": {"x": 1.6, "y": 1.6, "z": 0.8}})
fig.write_image("outputs/plotly-pca-3d.png", width=700, height=550,
scale=1.5)
variance explained, %: [29.4, 21.9, 7.0]
sample condition batch PC1 PC2 PC3
S01 control b1 -10.5 -6.2 3.9
S02 control b2 -7.7 8.7 -6.4
S03 control b1 -10.8 -5.3 -2.8
S04 control b2 -7.1 9.6 6.6
S05 control b1 -11.4 -5.8 -0.0
S06 control b2 -5.3 9.5 -1.8
S07 treated b1 7.4 -10.0 -3.4
S08 treated b2 10.3 4.2 -1.4
S09 treated b1 6.4 -8.8 1.4
S10 treated b2 11.4 7.0 -5.9
S11 treated b1 6.7 -9.5 1.3
S12 treated b2 10.5 6.6 8.4

3D scatter of 12 samples on the first three principal components, blue for control and orange for treated, circles for batch b1 and diamonds for b2. Control sits at negative PC1 and treated at positive PC1, and b1 sits at negative PC2 and b2 at positive PC2.

write_html keeps the figure interactive. include_plotlyjs="cdn" loads Plotly from a CDN, which keeps the file small; the default embeds the full library, so the file opens offline. write_image exports a static file, and the extension picks PNG, SVG, or PDF.

fig.write_html("outputs/plotly-pca-3d.html", include_plotlyjs="cdn")
fig.write_image("outputs/plotly-pca-3d.svg", width=700, height=550)
fig.write_image("outputs/plotly-pca-3d.pdf", width=700, height=550)

Static export runs through Kaleido 1.x, which drives a local copy of Chrome. Plotly 7 has no Orca support and no engine= argument, so older code that passes engine="kaleido" stops with a TypeError. If Chrome is missing, the plotly_get_chrome command downloads a compatible copy. Pass width, height, and scale on every call, or set them once with pio.defaults.default_width, pio.defaults.default_height, and pio.defaults.default_scale.

The plotly.py project gives its Zenodo software record as the citation for the library.

  • Plotly Express overview

    The overview shows how named columns control marks, colors, hover values, and plot types. Its examples help choose between a whole Express figure and later figure updates.

  • Plotly facet plots

    The facet guide explains independent axes, category order, and annotation labels. It documents the short callback used here to remove the gene-name prefix from each panel title.