Knowing that a figure is just structured data explains how every update, export and integration works.
A Plotly figure is a tree of attributes with two main branches:
data: a list of traces. Each trace is one series of a given type, such asscatter,bar,histogramorheatmap, with its ownx,y,marker,nameand so on.layout: everything that is not data: title, axes (xaxis,yaxis), legend, margins, size, template, annotations and shapes.
(A third branch, frames, holds animation frames.)
In Python the figure is a plotly.graph_objects.Figure object, which validates every attribute: misspell marker.colour and you get an error listing valid names instead of a silently ignored setting. fig.to_dict() and fig.to_json() show the raw structure, and print(fig) displays it compactly.
Rendering does not happen in Python at all. The figure is serialized to JSON and handed to plotly.js, a JavaScript library, in a notebook, a browser tab or an HTML file. That is why Plotly charts are interactive by default: hover tooltips, box zoom, pan, double-click to reset, and clicking legend entries to hide traces.
There are two ways to build figures:
- Plotly Express (
import plotly.express as px): one function call per chart from a DataFrame, returning a ready-made figure. - Graph objects (
import plotly.graph_objects as go): construct traces and layout yourself for full control.
Both produce the same Figure class, so you can start with Express and refine with graph-object methods.
Example
import plotly.graph_objects as go
fig = go.Figure(
data=[go.Bar(x=["a", "b", "c"], y=[3, 1, 2], name="sales")],
layout=go.Layout(title=dict(text="Sales by product")),
)
d = fig.to_dict()
print(list(d)) # ['data', 'layout']
print(d["data"][0]["type"]) # bar
print(fig.layout.title.text) # Sales by product
try:
go.Bar(marker=dict(colour="red")) # typo is caught
except ValueError as e:
print(str(e).splitlines()[2]) # Did you mean "color"?
fig.write_html("sales.html") # open in a browser: fully interactiveRemember
- A figure = list of traces (
data) +layout(+ optionalframes) - plotly.js renders the JSON in the browser, which makes charts interactive
- Graph objects validate attribute names and values
Watch out for
- Expecting matplotlib-style rendering in Python; output always needs a browser-like environment or an export step.