Hiding two graphs when legend clicked on

Greetings

I have generated the following plots from formula1 data, where, px.line() and px.scatter() was used seperately. This was done as I would like to indicate the tyre used by the driver for each lap (which was shown by px.scatter()) and px.line plotted the trace for lap times for a driver

The graph:

When clicking on a driver(px.line()) in the legend, usually the graph clicked on, becomes invisible. In my case, The scatter plot for that line graph is still evident, observe below


Is it possible to make the scatter plot and line plot, that would be 2 plots, invisible when clicking on the driver (line plot) alone?

Two things here that might solve what you are trying to do

  1. You can do a line plot and add markers by setting mode="lines+markers"
  2. You can group traces in the legend with the keyword legendgroup

Thank you for your response @RenaudLN, the reason I do not want to use a line plot alone, is because I would like to control the colour and symbols of the scatter plot independently from the line plot’s markers, but dependant on another column in my dataframe.

I’m also unable to use legendgroup because that only plotly.graph_objects can be used for that.

  1. You can control color from the markers independently from the color of the lines
  2. plotly.express creates a figure object which you can then update the same way you would with plotly.graph_objects instances

Example with lines+markers:

import numpy as np
import pandas as pd
import plotly.express as px

data = pd.DataFrame(np.random.rand(100, 2), columns=["A", "B"]).reset_index()

fig = px.line(
    data,
    x="index",
    y=["A", "B"]
)
fig.update_traces(
    mode="lines+markers",
    marker_color=data["index"].between(25,75).map({True: "magenta", False: "green"})
)
fig.show()

1 Like

And with legendgroup

import numpy as np
import pandas as pd
import plotly.express as px

data = pd.DataFrame(np.random.rand(50, 2), columns=["A", "B"]).reset_index()

fig = px.line(
    data,
    x="index",
    y=["A", "B"]
)

scatter1 = px.scatter(
    data.query("15 <= index < 35"),
    y=["A", "B"]
).update_traces(marker_color="gray", marker_size=8, name="Tyre 1")

scatter2 = px.scatter(
    data.query("index <15 | index >= 35"),
    y=["A", "B"]
).update_traces(marker_color="cyan", marker_size=8, name="Tyre 2")

fig.add_traces(
    scatter1.data
)
fig.add_traces(
    scatter2.data
)

for i, trace in enumerate(fig.data):
    if i in [3, 5]:
        trace.showlegend = False
    
fig.show()

1 Like

Jesus Christ. Thank you so much @RenaudLN. I will most certainly use these examples.

Mate, I have replicated this example in my code, in the attached link and I have run into another problem. In the context of your example, the values of other indices/rows (eg. beyond index 50) are taking on the value of the first 50. I have attached the link to my other post in this reply of yours. Any help would be appreciated.