Change visual properties based on trace name or other current values.
Conditional styling
Plotly · Module
Applies a callback to each figure trace that matches optional selection criteria. The callback can inspect and update traces individually, making conditional trace changes straightforward.
Call for_each_trace with a function that receives one trace at a time. The function can inspect each trace and mutate it, while selector, row, col, and secondary_y restrict which traces are visited.
fig.for_each_trace(fn, selector=None, row=None, col=None, secondary_y=None)| Name | Type | Description |
|---|---|---|
fn | callable | Function that inputs a single trace object. |
selector | dict | function | int | str | None | Dictionary, function, integer, string, or None selection criterion; None selects all traces. |
row | int | None | Subplot row to restrict the operation to. |
col | int | None | Subplot column to restrict the operation to. |
secondary_y | bool | None | Whether to restrict selection to the secondary y-axis. |
The documentation describes the operation as applying a function to matching traces; it does not specify a separate return value in the available method entry.
selector visits every trace in the figure.import plotly.express as px
fig = px.scatter(
px.data.iris(),
x="sepal_width",
y="sepal_length",
color="species",
)
fig.for_each_trace(
lambda trace: trace.update(marker_symbol="square")
if trace.name == "setosa" else None
)
fig.show()Creates an Iris scatter plot and changes the marker symbol only for the trace named setosa.
Conditional styling
Type-based processing
Subplot-specific edits
for_each_trace do?It applies a callback to every trace that meets the selection criteria. The callback receives a single trace, so it can make decisions from that trace’s current properties before updating it.
Follow-up: How would you select only scatter traces? Use selector="scatter", which the documentation defines as equivalent to dict(type="scatter").
The callback is the first argument, and the optional selector, row, col, and secondary_y arguments control which traces are considered. With no selector, all traces are selected.
Follow-up: How can selection depend on multiple trace properties? Pass a dictionary containing the required properties; all keys and exact values must match.
Use a function selector that accepts one trace and returns a boolean. Plotly evaluates it for each trace and selects the ones for which it returns True.
Follow-up: What is a useful advantage over a fixed dictionary? The predicate can inspect dynamic trace state and apply conditional logic.
update_tracesfor_each_annotationfor_each_xaxisfor_each_yaxisfor_each_layout_image