import plotly.express as px★High-level API — the recommended starting point.import plotly.graph_objects as go★Low-level building blocks: figures, traces, layout.from plotly.subplots import make_subplotsMulti-panel / mixed-type / dual-axis figures.import plotly.io as pioRenderers, templates, JSON & image I/O.df = px.data.tips()★Built-in demo data:iris,gapminder,stocks…pio.renderers.default = "browser"Wherefig.show()draws (notebook·vscode·browser).plotly.__version__ # 7.0v7 renders with Plotly.js 4.x.px.scatter(df, …) # pandas · polars · pyarrowexpressNarwhals-native (6.0+): Express accepts any Narwhals-compatible frame directly — no in-memory copy.
fig = px.scatter(df, x="a", y="b")★expressPoints; addcolor/sizeto encode more.px.line(df, x="t", y="v", color="grp")★One connected line per group.px.bar(df, x="cat", y="n", barmode="group")★group·stack·relative.px.area(df, x="t", y="v", color="grp")Stacked area over a shared x.px.funnel(df, x="n", y="stage")Stage-to-stage drop-off.px.timeline(df, x_start=, x_end=, y="task")Gantt-style timeline.
px.histogram(df, x="a", nbins=30)★histnorm=to normalize;histfunc=to aggregate.px.box(df, x="grp", y="v")★Quartiles + whiskers;points="all"to overlay.px.violin(df, y="v", box=True)KDE shape + optional inner box.px.strip(df, x="grp", y="v")Jittered raw points.px.ecdf(df, x="a")Empirical cumulative distribution.px.density_heatmap(df, x=, y=)2-D histogram as a heatmap.px.density_contour(df, x=, y=)2-D KDE contour lines.
px.pie(df, names="cat", values="n")★Proportions of a whole;hole=0.4for a donut.px.sunburst(df, path=["a","b","c"], values="n")★Nested rings from a column hierarchy.px.treemap(df, path=[…], values="n")★Nested rectangles sized by value.px.icicle(df, path=[…], values="n")Hierarchy as stacked bars.px.funnel_area(names=, values=)Funnel drawn as proportional areas.
px.scatter_3d(df, x=, y=, z=, color=)Rotatable 3-D points.px.scatter_map(df, lat=, lon=, zoom=3)★Tile map (MapLibre); wasscatter_mapbox.px.choropleth(df, locations=, color=)Filled geographic regions.px.imshow(img_or_matrix)★Show an image, matrix, or labelled heatmap.px.scatter_matrix(df, dimensions=[…])Pairwise scatter-plot matrix (SPLOM).px.parallel_coordinates(df, dimensions=)Multi-axis lines for high-dim data.
color="col"★Discrete → legend; continuous → colorbar.size="col"Bubble size by value;size_max=to cap.symbol="col", line_dash="col"Marker shape / line dash by variable.facet_col="col", facet_row="col"★Small-multiple panel grid.animation_frame="year"★Adds a play button that steps across frames.hover_name="id", hover_data=["x","y"]Control the tooltip contents.text="col"Print data labels on the marks.trendline="ols"Fit a line (needsstatsmodels):ols·lowess.
fig = go.Figure(data=[go.Scatter(x=x, y=y)])★graph_objectsAssemble a figure from a list of traces.go.Figure(data=[…], layout=go.Layout(title="…"))data= the traces,layout= everything else.go.Scatter(x=, y=, mode="markers+lines")★mode=markers·lines·text(mix with +).fig.add_trace(go.Bar(x=, y=))★Layer another trace onto the figure.fig.data · fig.layoutInspect the trace tuple and the layout tree.go.Figure(fig_dict)A figure is really just a nested dict.
go.Scatter · go.Scattergl★Lines/markers;gl= WebGL for big data.go.Bar · go.Histogram★Bars and binned counts.go.Heatmap · go.ContourMatrix as color grid / iso-contours.go.Box · go.ViolinDistribution summaries.go.Scatter3d · go.Surface · go.Mesh3d3-D points, surfaces, meshes.go.Choropleth · go.ScattergeoGeographic maps.go.Candlestick · go.Ohlc · go.WaterfallFinancial charts.go.Sankey · go.Indicator · go.TableFlows, KPI gauges, tables.
fig.update_layout(title="…", legend_title="…")★Set any layout property.fig.update_traces(marker_size=10, selector=dict(type="scatter"))★selector=targets which traces to edit.fig.update_xaxes(type="log", range=[0,5])Per-axis tweaks (update_yaxestoo).fig.add_hline(y=0) · fig.add_vrect(x0=, x1=)Reference lines & shaded bands.fig.add_annotation(x=, y=, text="peak")Point callouts with optional arrows.marker_color="red" ≡ marker=dict(color="red")★Magic underscore flattens nested props.
from plotly.subplots import make_subplots★The helper for multi-panel figures.fig = make_subplots(rows=2, cols=2, subplot_titles=(…))★A grid of empty panels.fig.add_trace(go.Scatter(…), row=1, col=2)★Place a trace in a specific panel.make_subplots(…, shared_xaxes=True)Link axes across panels.specs=[[{"type":"domain"}, {"type":"scene"}]]Mix types: pie (domain), 3-D (scene), maps.specs=[[{"secondary_y":True}]]Dual y-axis in one panel.
fig.update_layout(xaxis_title="…", yaxis_title="…")★Axis titles the quick way.fig.update_layout(width=800, height=500, margin=dict(l=40))Explicit size & margins.fig.update_layout(legend=dict(orientation="h", y=1.1))Reposition / reorient the legend.fig.update_layout(hovermode="x unified")★One combined tooltip across traces.fig.update_layout(showlegend=False)Hide the legend entirely.fig.update_layout(barmode="stack", bargap=0.2)Bar stacking & spacing.
template="plotly_white"★plotly·plotly_white·plotly_dark·ggplot2·seaborn·simple_white.pio.templates.default = "plotly_white"Set the theme once, globally.color_discrete_sequence=px.colors.qualitative.Set2Categorical palette.color_continuous_scale="Viridis"★Sequential scale for numeric color.color_discrete_map={"A":"red", "B":"blue"}Pin exact colors to categories.range_color=[0, 100]Clamp the continuous colorbar.
zoom · pan · box-select · hover · legend-toggle★Free on every figure — no config needed.hovertemplate="%{x}: %{y:.2f}<extra></extra>"Custom tooltip;<extra>hides the trace box.fig.update_layout(hovermode="x unified")Shared crosshair tooltip.fig.update_xaxes(rangeslider_visible=True)Add a range slider under the x-axis.fig.update_layout(updatemenus=[…])Dropdowns & buttons.fig.show(config=dict(scrollZoom=True))Toolbar / behavior config.
fig.show()★Render in the active renderer (notebook/browser).fig.write_html("f.html")★Standalone interactive file — opens anywhere.fig.write_html("f.html", include_plotlyjs="cdn")Smaller file; loads Plotly.js from a CDN.fig.write_image("f.png", scale=2)★Static raster/vector — needskaleido.fig.to_json() · fig.to_dict()Serialize the figure to embed or store.
px.scatter(df, …)★expressOne call, tidy DataFrame in → whole figure out.go.Figure(data=[…], layout=…)★graph_objectsAssemble traces by hand — total control.every px.* returns a go.Figure★So you can freely mix both styles.px when: explore · facet · animate · color-mapFast, expressive, DataFrame-native.go when: mixed subplots · dual-axis · fine controlThe things a single px call can't express.…then always fig.update_layout()★Refinement works the same on both.rule: start in px, drop to go only when neededThe practical workflow.
px wants long / tidy datareshapeMelt wide→long, or use px's wide-form mode.fig.write_image(…)kaleido v1Static export needskaleido ≥1.0(orca & theengine=arg are gone; Kaleido finds an existing Chrome).scatter_mapbox → scatter_mapremoved in v7v7 removes the old*mapboxtrace types &mapboxAccessToken— use the MapLibre*mapfunctions.fig.show() in a .py scriptNeeds a renderer (browser) — else nothing appears.update_traces hits ALL tracesPassselector=to target a subset.big scatter (>10k pts)Usego.Scattergl(WebGL) to stay smooth.category order looks randomSetcategory_orders=or axiscategoryorder.