Hi all,
I’m trying to plot multiple shapes that will be grouped based on some criteria and have them appear on the legend. Since there can be a lot of shapes, I wanted to have a single legend entry for each shape group. The docs explain how to do this (https://plotly.com/python/legend/#grouped-legend-items), however, it doesn’t seem to work for shapes. If I add showlegend=False
to one of the shapes in my group, it will not toggle that shape when clicking the legend item. Here’s some code to illustrate:
from dash import Dash, dcc, html
import plotly.graph_objects as go
if __name__ == "__main__":
fig = go.Figure()
fig.add_trace(go.Scatter(
x=[1, 2, 3],
y=[2, 1, 3],
legendgroup="group",
name="First trace",
mode="markers",
marker=dict(color="Crimson", size=10)
))
fig.add_trace(go.Scatter(
x=[1, 2, 3],
y=[2, 2, 2],
legendgroup="group",
name="Second trace",
mode="lines",
line=dict(color="Crimson"),
showlegend=False,
))
fig.add_shape(
type="line",
x0=0,
y0=1,
x1=4,
y1=1,
line_width=3,
line_dash="dot",
showlegend=True,
legendgroup="shapes",
name="First shape",
)
fig.add_shape(
type="line",
x0=0,
y0=3,
x1=4,
y1=3,
line_width=3,
line_dash="dot",
showlegend=False,
legendgroup="shapes",
name="Second shape",
)
fig.update_layout(title="Try Clicking on the Legend Items!")
app = Dash()
app.layout = html.Div([dcc.Graph(figure=fig)])
app.run_server(debug=True, use_reloader=True)
This will result in a plot like the one below. Toggling the first trace in the legend will hide both traces because they are in the same legendgroup (expected). Toggling the first shape in the legend will hide only the first shape, leaving the other one visible.
Is it possible to get this to work? Making the shapes traces instead is not an option in my case. I’m using Dash version 2.12.0 and plotly version 5.16.0.