Skip to content

Plotly

Plotly draws interactive charts for the browser: hover tooltips, zoom, pan and legend clicks that hide series. Plotly Express (px) builds a whole figure from a DataFrame in one call; fig.update_* methods then change its layout, axes and traces. The result is a plotly.graph_objects.Figure that you show, save as HTML or embed in a web app. Examples use data/sales.csv and data/houses.csv.

I want to… Use… Example
a line chart px.line px.line(df, x="date", y="visits", markers=True)
one line per group color= px.line(df, x="month", y="revenue", color="channel")
bars px.bar px.bar(df, x="region", y="revenue", color="channel", barmode="group")
values on the bars text_auto= px.bar(..., text_auto=".3s") → 427k
a 100% stacked bar barnorm="percent" in the layout fig.update_layout(barnorm="percent")
a scatter with details on hover px.scatter + hover_name, hover_data px.scatter(df, x="sqft", y="price", hover_name="house_id")
bubble size size= px.scatter(..., size="bedrooms", size_max=12)
a trend line trendline= (needs statsmodels) px.scatter(..., trendline="ols") or "lowess"
a histogram px.histogram px.histogram(df, x="price", nbins=50, marginal="box")
a mean per group without aggregating histfunc= px.histogram(df, x="plan", y="churned", histfunc="avg")
distributions per group px.box, px.violin, px.strip, px.ecdf px.box(df, x="area", y="price", points="outliers")
a heatmap of a matrix px.imshow px.imshow(corr, text_auto=".2f", zmin=-1, zmax=1)
a 2-D histogram for many points px.density_heatmap px.density_heatmap(df, x="sqft", y="price")
parts of a whole, hierarchy px.pie, px.sunburst, px.treemap px.treemap(df, path=["category", "product"], values="revenue")
small multiples facet_col=, facet_row= px.histogram(..., facet_col="area", facet_col_wrap=4)
an animation over time animation_frame= + fixed range px.bar(..., animation_frame="month", range_y=[0, top])
nice axis and tooltip names labels= labels={"revenue": "Revenue (USD)"}
a fixed category order category_orders= category_orders={"plan": ["basic", "standard", "premium"]}
fixed colors per category color_discrete_map= color_discrete_map={"online": "#0173b2", "store": "#de8f05"}
a clean background template= template="plotly_white", or px.defaults.template = "plotly_white"
a log axis log_x=, log_y= px.scatter(..., log_y=True)
title, legend, margins fig.update_layout fig.update_layout(title="...", legend_title_text="Channel")
axis format fig.update_yaxes fig.update_yaxes(tickformat=",", rangemode="tozero")
custom tooltip text fig.update_traces(hovertemplate=...) "%{x}: %{y:,.0f} USD<extra></extra>"
one tooltip for all series hovermode= fig.update_layout(hovermode="x unified")
a reference line or band fig.add_hline, fig.add_vrect fig.add_hline(y=5000, line_dash="dash", annotation_text="target")
a text label with an arrow fig.add_annotation fig.add_annotation(x=x, y=y, text="peak")
add a series to a px figure fig.add_scatter, fig.add_trace fig.add_scatter(x=..., y=..., mode="markers", name="...")
a range slider for dates fig.update_xaxes(rangeslider_visible=True)
short facet titles fig.for_each_annotation lambda a: a.update(text=a.text.split("=")[-1])
different traces side by side make_subplots + go traces make_subplots(rows=1, cols=2)
save an interactive chart fig.write_html fig.write_html("output/chart.html", include_plotlyjs="cdn")
an HTML snippet for a web page fig.to_html fig.to_html(full_html=False, include_plotlyjs="cdn")
a PNG or SVG fig.write_image (needs kaleido>=1) fig.write_image("output/chart.png", scale=2)
Family Functions Typical call
trends line, area, scatter px.line(df, x="date", y="visits", color="channel", line_shape="spline")
comparison bar, funnel, timeline px.bar(df, x="value", y="name", orientation="h")
relations scatter, scatter_matrix, parallel_coordinates, scatter_3d px.scatter_matrix(df, dimensions=["sqft", "price"], color="area")
distributions histogram, box, violin, strip, ecdf px.violin(df, x="plan", y="charges", box=True, points=False)
2-D density density_heatmap, density_contour px.density_heatmap(df, x="a", y="b", nbinsx=40)
matrices and images imshow px.imshow(pivot, text_auto=True, aspect="auto")
parts of a whole pie, sunburst, treemap, icicle, funnel_area px.sunburst(df, path=["region", "channel"], values="revenue")
categories flow parallel_categories px.parallel_categories(df, dimensions=["plan", "contract"])
polar, ternary scatter_polar, line_polar, bar_polar, scatter_ternary px.line_polar(df, r="value", theta="axis", line_close=True)
maps scatter_geo, choropleth, scatter_map, density_map, choropleth_map px.choropleth(df, locations="iso3", color="gdp") (the *_mapbox functions are gone in Plotly 7)

Every function takes a DataFrame in long (tidy) format plus column names. Wide data works for line, bar and area too: px.line(wide_df) draws one line per column.

Argument Does Example
color= color by a column; text → distinct colors, numbers → a color scale color="channel"
color_discrete_sequence= colors for categories px.colors.qualitative.Safe (color-blind friendly)
color_discrete_map= an exact color per category {"online": "#0173b2"}
color_continuous_scale= a scale for numeric color "Viridis", "RdBu_r"; with range_color=[0, 1]
symbol=, line_dash=, pattern_shape= marker shape, dash, bar fill pattern symbol="has_pool"
size=, size_max= bubble size size="bedrooms", size_max=15
opacity= transparency for overlapping points opacity=0.5
hover_name= bold first line of the tooltip hover_name="house_id"
hover_data= extra tooltip columns: a list, or a dict of formats {"price": ":$,.0f", "date": "|%Y-%m-%d", "area": False}
custom_data= columns for %{customdata[0]} in a hovertemplate custom_data=["house_id"]
text= a text label on each mark text="product"
labels= rename columns in axes, legend and tooltips labels={"sqft": "Size (sq ft)"}
facet_col=, facet_row= one panel per value facet_col="neighborhood"
facet_col_wrap= panels per row facet_col_wrap=4
facet_col_spacing=, facet_row_spacing= gap between panels 0.04
animation_frame= one frame per value, with a play button and slider animation_frame="month"
animation_group= which marks are the same object across frames animation_group="country"
range_x=, range_y= fixed axis ranges (needed for a stable animation) range_y=[0, 100_000]
category_orders= order of categories, facets and frames {"plan": ["basic", "standard", "premium"]}
log_x=, log_y= log axes log_y=True
barmode= "relative" (stacked, default), "group", "overlay" barmode="group"
title=, template=, width=, height= figure options height=400

hover_data formats use d3 syntax after a colon: ":,.0f" (thousands separator), ":.1%", ":$,.0f". For dates, "|%Y-%m-%d" uses a pipe. False hides a column that would show by default.

import pandas as pd
import plotly.express as px
houses = pd.read_csv("data/houses.csv")
fig = px.scatter(houses, x="sqft", y="price", color="neighborhood",
hover_name="house_id",
hover_data={"price": ":$,.0f", "neighborhood": False})
print(len(fig.data), "traces: one per color") # px makes one trace per group
print(fig.data[0].hovertemplate) # what the tooltip shows
fig = px.histogram(houses, x="price", facet_col="neighborhood", facet_col_wrap=4)
print(fig.layout.annotations[0].text) # default facet title: column=value
fig.for_each_annotation(lambda a: a.update(text=a.text.split("=")[-1]))
print(fig.layout.annotations[0].text)
Output
8 traces: one per color
<b>%{hovertext}</b><br><br>sqft=%{x}<br>price=%{y:$,.0f}<extra></extra>
neighborhood=Riverside
Riverside
Method Changes Example
fig.update_layout(...) title, legend, margins, size, fonts, hover fig.update_layout(title="...", height=400, margin={"t": 60})
magic underscores a nested property in one keyword legend_title_text="Channel", xaxis_title="Month", font_size=13
fig.update_xaxes(...), update_yaxes(...) every x or y axis, including facets tickformat=",.0f", tickangle=-45, rangemode="tozero", dtick="M3"
fig.update_yaxes(matches=None) independent y ranges per facet
fig.update_traces(...) every trace, or only some with selector= fig.update_traces(marker_size=6, selector={"mode": "markers"})
fig.update_traces(texttemplate=..., textposition="outside") labels on bars texttemplate="%{y:,.0f}"
fig.add_hline, add_vline a reference line fig.add_vline(x="2024-04-08", line_dash="dot")
fig.add_hrect, add_vrect a shaded band fig.add_vrect(x0=a, x1=b, fillcolor="gray", opacity=0.15, line_width=0)
fig.add_annotation text with an optional arrow fig.add_annotation(x=x, y=y, text="peak", showarrow=True)
fig.add_scatter, add_bar, add_trace(go.X(...)) another series fig.add_scatter(x=d, y=v, mode="lines", name="7-day mean")
fig.update_layout(hovermode=...) "closest", "x", "x unified" hovermode="x unified" for time series
fig.update_layout(legend={...}) legend position legend={"orientation": "h", "y": 1.1}
hovertemplate part Shows
%{x}, %{y} the x and y values
%{y:,.0f}, %{y:.1%}, %{x|%b %Y} formatted values (d3 formats; dates after |)
%{customdata[0]} a column passed with custom_data=
%{hovertext} the hover_name column
<br>, <b>…</b> a line break, bold text
<extra></extra> hide the trace-name box next to the tooltip
sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])
sales["month"] = sales["order_date"].dt.strftime("%Y-%m")
keys = ["month", "category", "channel"]
monthly = sales.groupby(keys, as_index=False)["revenue"].sum()
top = monthly["revenue"].max()
fig = px.bar(monthly, x="category", y="revenue", color="channel", barmode="group",
animation_frame="month", range_y=[0, top * 1.1], # fixed y across frames
category_orders={"category": ["Electronics", "Home", "Sports",
"Clothing", "Beauty", "Books"]},
labels={"revenue": "Revenue (USD)", "category": "", "channel": "Channel"},
color_discrete_sequence=px.colors.qualitative.Safe,
template="plotly_white", title="Monthly revenue by category, 2023–2024")
fig.update_traces(hovertemplate="%{x}: %{y:,.0f} USD<extra></extra>")
fig.update_yaxes(tickformat=",")
print(len(fig.frames), "frames,", fig.frames[0].name, "to", fig.frames[-1].name)
best = monthly.loc[monthly["revenue"].idxmax()]
print(best["month"], best["category"], best["channel"], round(best["revenue"]))
fig.show()
Output
24 frames, 2023-01 to 2024-12
2024-12 Electronics store 92767
Monthly revenue by category and channel, animated by month · Open the interactive chart in a new tab

Press play or drag the slider to step through the 24 months. Without range_y, each frame rescales its own y-axis and the bars seem to jump. hovertemplate changes the tooltip of the first frame; the frames keep Plotly Express’s default tooltip.

Plotly Express returns a go.Figure. Build one yourself for mixed chart types or a custom grid.

import plotly.graph_objects as go
from plotly.subplots import make_subplots
by_area = houses.groupby("neighborhood")["price"].median().sort_values()
fig = make_subplots(rows=1, cols=2, subplot_titles=["Median price", "Price vs size"])
fig.add_trace(go.Bar(x=by_area.to_numpy(), y=by_area.index, orientation="h"),
row=1, col=1)
fig.add_trace(go.Scatter(x=houses["sqft"], y=houses["price"], mode="markers",
marker={"size": 4, "opacity": 0.4}), row=1, col=2)
fig.update_layout(showlegend=False, template="plotly_white", height=380)
print([trace.type for trace in fig.data], fig.layout.xaxis2.anchor)
Output
['bar', 'scatter'] y2
Graph object Draws
go.Scatter(mode="lines" | "markers" | "lines+markers") lines and points
go.Scattergl the same with WebGL, for 100,000+ points
go.Bar, go.Histogram, go.Box, go.Violin bars and distributions
go.Heatmap, go.Contour grids of values
go.Pie, go.Sunburst, go.Treemap parts of a whole
go.Indicator a big KPI number with a delta
go.Table a table
Call Result
fig.show() opens the chart in a notebook output cell or a browser tab; it saves nothing
fig.write_html("output/c.html", include_plotlyjs="cdn") a small file that loads plotly.js from the web
fig.write_html("output/c.html") a self-contained file (plotly.js embedded, about 4.6 MB) that works offline
fig.to_html(full_html=False, include_plotlyjs="cdn") a <div> string to put into your own page or template
fig.write_image("output/c.png", scale=2) a static image; needs pip install "kaleido>=1" and a Chrome browser
fig.to_json(), plotly.io.from_json(text) the figure as JSON and back
pio.renderers.default = "browser" where fig.show() goes: "notebook", "vscode", "browser", "png"
from pathlib import Path
Path("output").mkdir(exist_ok=True)
fig.write_html("output/houses.html", include_plotlyjs="cdn")
html = Path("output/houses.html").read_text(encoding="utf-8")
print("cdn.plot.ly" in html, html.count("<script")) # the library comes from a CDN
Output
True 3
Trap Symptom Fix
expecting fig.show() to save no file appears fig.write_html(...) or fig.write_image(...)
fig.write_image without kaleido RuntimeError: Image export requires the Kaleido package, v1.0.0 or greater pip install "kaleido>=1" (it uses a local Chrome)
px.scatter_mapbox and other *_mapbox functions AttributeError in Plotly 7 px.scatter_map, px.density_map, px.choropleth_map
titlefont= and other old layout names ValueError: Invalid property specified ... 'titlefont' title_font=... or title={"font": {...}}
reading fig.to_dict() or fig.to_json() arrays appear as {'dtype': 'i1', 'bdata': 'AQI='} read fig.data[0].y (a NumPy array) instead
an animation without range_x/range_y axes rescale on every frame fix the ranges
one long-format column with many categories in color= a huge legend, repeated colors aggregate, filter the top N, or use facet_col
px.bar(..., barnorm="percent") TypeError: bar() got an unexpected keyword argument 'barnorm' fig.update_layout(barnorm="percent"), or px.histogram(..., histfunc="sum", barnorm="percent")
a numeric category column (a year, an id) in color= a continuous color bar instead of distinct colors df["year"].astype(str)
facet titles neighborhood=Lakeview long panel titles fig.for_each_annotation(...) as above
facets in data order panels in a random-looking order category_orders={"col": [...]}
trendline="ols" without statsmodels ModuleNotFoundError: No module named 'statsmodels' pip install statsmodels
a chart of a million rows huge HTML file, slow browser aggregate, sample, px.density_heatmap, or render_mode="webgl"
a self-contained HTML of 4.6 MB per chart big e-mails and repos include_plotlyjs="cdn" (needs internet to view)
hovertemplate and an animation frames lose the custom tooltip set the template on each frame’s traces too, or use hover_data formats