Incremental figure construction
Start with go.Figure() and add traces one at a time.
Plotly · Function
Adds a graph-object trace or trace dictionary to a Plotly figure. Subplot coordinates and secondary-axis options can control where the trace is placed.
add_trace accepts a graph-object trace or a trace dictionary and appends it to a figure. For figures made with make_subplots, row and col select the destination subplot; the method returns the figure so calls can be chained.
Figure.add_trace(trace, row=None, col=None, secondary_y=None, exclude_empty_subplots=False)| Name | Type | Description |
|---|---|---|
trace | BaseTraceType or dict | Trace object or dictionary to add. A dictionary uses type to identify the trace type; without it, scatter is assumed. |
row | 'all', int, or None | One-based subplot row index; all addresses all rows in selected columns. Valid for subplot figures. |
col | 'all', int, or None | One-based subplot column index; all addresses all columns in selected rows. Valid for subplot figures. |
secondary_y | boolean or None | Whether to place the trace on the secondary y-axis. |
exclude_empty_subplots | boolean | When true, do not add the trace to subplots that do not already contain traces. |
The figure on which add_trace was called; return type BaseFigure.
add_trace to build a graph-object figure incrementally, starting with an empty figure if needed.go.Scatter or go.Bar.append_trace is an alternative with similar insertion behavior, but it does not return the figure.import plotly.graph_objects as go
from plotly.subplots import make_subplots
fig = make_subplots(rows=1, cols=2)
fig.add_trace(go.Scatter(y=[4, 2, 1], mode="lines"), row=1, col=1)
fig.add_trace(go.Bar(y=[2, 1, 3]), row=1, col=2)
fig.show()Creates a two-panel figure and adds a different graph-object trace to each subplot.
Start with go.Figure() and add traces one at a time.
Use make_subplots and provide row and col for each trace.
Add a trace to a secondary y-axis in a configured subplot.
Figure.add_trace accept and return?add_trace adds one graph-object trace, such as go.Scatter or go.Bar, to a figure and returns the figure. A trace dictionary is also accepted.
Follow-up: How would you target a subplot? Create the figure with make_subplots, then pass its one-based row and col values to add_trace.
Pass row and col to select the subplot destination. The row index starts at 1, and these arguments apply to figures created with the subplot helper.
Follow-up: What happens when row='all'? It addresses all rows in the specified column or columns.
A trace dictionary must identify its trace kind with the type property, for example scatter or bar. If type is omitted, Plotly assumes scatter.
Follow-up: Why might using a graph-object constructor be preferable? It makes the trace class explicit and supplies its typed properties directly.
Figure.add_tracesFigure.append_traceplotly.subplots.make_subplotsgo.Scattergo.Bar