Plotly Cheat Sheet
Plotly reference for building interactive charts with the Express and Graph Objects APIs, subplots, and exporting to HTML or images.
Plotly Express Basics
High-level API for quick interactive charts.
import plotly.express as pxfig = px.scatter( df, x="gdp_per_cap", y="life_exp", color="continent", size="population", hover_name="country", log_x=True,)fig.update_layout(title="Life Expectancy vs GDP")fig.show()fig2 = px.line(df, x="date", y="value", color="category")fig2.write_html("chart.html") # export interactive HTML
Graph Objects API
Low-level API for fine-grained control.
import plotly.graph_objects as gofig = go.Figure()fig.add_trace(go.Scatter(x=x, y=y1, mode="lines+markers", name="series A"))fig.add_trace(go.Bar(x=x, y=y2, name="series B"))fig.update_layout( xaxis_title="X", yaxis_title="Y", template="plotly_dark",)
Subplots & Export
Combine multiple charts and export static images.
from plotly.subplots import make_subplotsfig = make_subplots(rows=1, cols=2, subplot_titles=("Left", "Right"))fig.add_trace(go.Scatter(x=x, y=y), row=1, col=1)fig.add_trace(go.Bar(x=x, y=y2), row=1, col=2)fig.write_image("out.png") # requires the kaleido package
Common Chart Types
Frequently used Express and Graph Objects charts.
- px.scatter- scatter plot
- px.line- line chart
- px.bar- bar chart
- px.histogram- histogram
- px.box / px.violin- distribution comparison across groups
- px.choropleth- geographic map colored by value
- px.sunburst / px.treemap- hierarchical part-to-whole charts
- go.Heatmap- matrix heatmap
Dash Interactive Callbacks
Wire a Plotly figure to reactive inputs in a Dash app.
from dash import Dash, dcc, html, Input, Outputimport plotly.express as pxapp = Dash(__name__)app.layout = html.Div([ dcc.Dropdown(df.continent.unique(), "Asia", id="continent"), dcc.Graph(id="gdp-chart"),])@app.callback(Output("gdp-chart", "figure"), Input("continent", "value"))def update_chart(continent): filtered = df[df.continent == continent] return px.scatter(filtered, x="gdp_per_cap", y="life_exp", size="population")if __name__ == "__main__": app.run(debug=True)
Custom Hover Templates & Annotations
Control exactly what appears in tooltips and add fixed annotations/shapes.
fig = go.Figure(go.Scatter( x=x, y=y, mode="markers", customdata=df[["country", "year"]], hovertemplate="<b>%{customdata[0]}</b><br>Year: %{customdata[1]}<br>Value: %{y:.2f}<extra></extra>",))fig.add_annotation(x=2020, y=100, text="Peak", showarrow=True, arrowhead=2)fig.add_shape(type="line", x0=2015, x1=2023, y0=80, y1=80, line=dict(dash="dash", color="red"))fig.add_hline(y=80, line_dash="dot", annotation_text="threshold")
Animations & Range Sliders
Build time-based animated frames and a scrollable range selector.
fig = px.scatter( df, x="gdp_per_cap", y="life_exp", animation_frame="year", animation_group="country", size="population", color="continent", range_x=[100, 100000], range_y=[20, 90], log_x=True,)fig.update_layout( updatemenus=[dict(type="buttons", buttons=[dict(label="Play", method="animate", args=[None])])],)fig2 = px.line(df, x="date", y="close")fig2.update_xaxes(rangeslider_visible=True)
WebGL Rendering for Large Datasets
Switch to WebGL traces so charts stay responsive past ~10k points.
import plotly.graph_objects as go# Scattergl instead of Scatter renders via WebGL, not SVGfig = go.Figure(go.Scattergl( x=large_df.x, y=large_df.y, mode="markers", marker=dict(size=3, opacity=0.4),))fig.update_layout(template="plotly_white")# px.scatter auto-upgrades to Scattergl above render_mode="webgl"fig2 = px.scatter(large_df, x="x", y="y", render_mode="webgl")
Performance & Deployment Notes
Considerations for shipping Plotly charts to production.
- fig.to_json() / fig.to_dict()- serialize a figure for transport to a JS frontend without re-plotting server-side
- include_plotlyjs="cdn"- write_html() option that links the JS library from a CDN instead of embedding ~3.5MB inline
- config={'displayModeBar': False}- pass to fig.show()/write_html() to hide the built-in toolbar for embedded dashboards
- fig.update_traces(selector=...)- apply style updates only to traces matching a dict/function selector, not all traces
- go.Figure(fig, layout=go.Layout(...))- efficient pattern for cloning a figure's data while overriding layout
- kaleido engine- headless Chromium-based renderer used by write_image(); pin its version for reproducible CI exports
Static image export (fig.write_image or fig.to_image) requires the separate kaleido package installed — without it, only fig.show() and fig.write_html() will work.