plotly / plotly.py

The interactive graphing library for Python :sparkles: This project now includes Plotly Express!
https://plotly.com/python/
MIT License
16.25k stars 2.55k forks source link

fig.add_vrect() items do not hide when clicking on grouped legend if showlegend=False #4705

Open pcubillos opened 3 months ago

pcubillos commented 3 months ago

Hi,

Here's a reproducible example below. Clicking on the legend group does not hide the second vrect (unlike for fig.add_trace(go.Scatter()) calls). I tried it on versions 5.23.0 and 5.19.0.

import plotly.graph_objects as go

fig = go.Figure()

fig.add_vrect(
    x0=1.0, x1=3.0,
    fillcolor="LightSalmon", opacity=0.3,
    layer="below", line_width=0,
    legendgrouptitle_text="Saturation",
    legendgroup='saturation',
    name='partial',
    showlegend=True,
)

fig.add_vrect(
    x0=3.5, x1=4.5,
    fillcolor="LightSalmon", opacity=0.3,
    layer="below", line_width=0,
    legendgroup='saturation',
    name='partial 2',
    showlegend=False,
)

fig.show()
lucas-schroeder commented 2 months ago

I got the same problem with Shapes and legendgroup. Only when all legends are set to visible they can be toggled together, otherwise only the one with showlegend=True. I'm using Pyhton 3.10.0 and Plotly 5.23.0. Here's a reproducible example:

import pandas as pd
import numpy as np
import plotly.graph_objects as go

data = {
    "Time": pd.date_range("2024-01-01", periods=20, freq="D"),
    "Value": np.random.randint(0, 100, size=20),
}
df = pd.DataFrame(data)

fig = go.Figure()
fig.add_trace(
    go.Scatter(
        x=df["Time"],
        y=df["Value"],
        name="From DataFrame",
        legendgroup="Data",
        legendgrouptitle=dict(text="Data"),
    )
)
shapes=[]

for i, idx in enumerate([1,5,6,14]):
    shapes.append(
        dict(
            type="rect",
            xref="x",
            yref="paper",
            x0=df["Time"][idx-1],
            y0=0,
            x1=df["Time"][idx+1],
            y1=1,
            line=dict(width=0),
            fillcolor="rgba(178, 222, 39, 0.3)",
            layer="below",
            name=f"Highlight {i}",
            legendgroup="Highlights",
            legendgrouptitle=dict(text="Highlights"),
            showlegend=True if i == 0 else False,
        )
    )

fig.update_layout(
    title="Highlighted data",
    xaxis_title="Time",
    yaxis_title="Value",
    shapes=shapes,
)

fig.show()