The legend in Plotly provides information about the traces in your plot. While often useful, there are situations where you might want to hide the legend. Check several ways to hide the legend in Plotly.
1. Hiding the Legend for the Entire Figure
The simplest way to hide the legend is to modify the layout of your figure and set the showlegend
attribute to False
.
import plotly.graph_objects as go
fig = go.Figure()
fig.add_trace(go.Scatter(x=[1, 2, 3], y=[4, 5, 6], name="Trace 1"))
fig.add_trace(go.Scatter(x=[1, 2, 3], y=[7, 8, 9], name="Trace 2"))
fig.update_layout(showlegend=False) # Hide the legend
fig.show()
This code creates a figure with two traces and then uses fig.update_layout(showlegend=False)
to hide the legend. This approach hides the legend for all traces in the figure.
2. Hiding the Legend for Individual Traces
You might want to hide the legend for some traces but not others. You can do this by setting the showlegend
attribute to False
for specific traces.
import plotly.graph_objects as go
fig = go.Figure()
fig.add_trace(go.Scatter(x=[1, 2, 3], y=[4, 5, 6], name="Trace 1", showlegend=False)) # Hide legend for this trace
fig.add_trace(go.Scatter(x=[1, 2, 3], y=[7, 8, 9], name="Trace 2")) # Legend will be shown for this trace
fig.show()
In this example, the legend is hidden only for “Trace 1” because showlegend=False
is set within the trace definition. “Trace 2” will still appear in the legend.
3. Using fig.update_traces() (For Modifying Existing Traces)
If you have already created your traces and want to modify them to hide the legend, you can use the fig.update_traces() method.
import plotly.graph_objects as go
fig = go.Figure()
fig.add_trace(go.Scatter(x=[1, 2, 3], y=[4, 5, 6], name="Trace 1"))
fig.add_trace(go.Scatter(x=[1, 2, 3], y=[7, 8, 9], name="Trace 2"))
fig.update_traces(showlegend=False, selector=dict(name="Trace 1")) # Hide legend for "Trace 1"
fig.show()
This code adds two traces and then uses fig.update_traces() with a selector to target only “Trace 1” and set its showlegend attribute to False.
Which Method to Use?
- Use
fig.update_layout(showlegend=False)
to hide the legend for the entire figure. This is the most common approach. - Use
showlegend=False
within the trace definition to hide the legend for individual traces. - Use fig.update_traces() when you need to modify existing traces to hide their legend entries. This is useful when you have already created your figure and need to make changes.