Is there is a way to hide all other lines on a figure, when I am hovering a single one?
Example:
JavaScript
x
9
1
import numpy as np
2
import plotly.express as px
3
4
np.random.seed(42)
5
data = np.random.randint(0, 10, (5, 10))
6
fig = px.line(data_frame=pd.DataFrame(data))
7
8
fig.show()
9
will produce:
and I want this, when I hover particular line (but without manually switching off all other lines and keeping X, Y axes dims):
UPD: inside jupyter notebook
Advertisement
Answer
JavaScript
1
42
42
1
import plotly.graph_objects as go
2
import numpy as np
3
import pandas as pd
4
5
# callback function for on_hover
6
def hide_traces_on_hover(trace, points, selector):
7
if len(points.point_inds)==1: # identify hover
8
i = points.trace_index # get the index of the hovered trace
9
f.data[i].visible = True # keep the hovered trace visible
10
# create a list of traces you want to hide
11
hide_traces = [l_trace for idx, l_trace in enumerate(f.data) if idx != i]
12
for l_trace in hide_traces: # iterate over hide_traces
13
l_trace.visible = 'legendonly' # hide all remaining traces
14
15
# callback function to unhide traces on click
16
def unhide_traces_on_click(trace, points, selector):
17
for l_trace in f.data:
18
l_trace.visible = True
19
20
# your sample data frame
21
np.random.seed(42)
22
data = np.random.randint(0, 10, (5, 10))
23
df = pd.DataFrame(data)
24
25
f = go.FigureWidget() # create figure widget
26
27
f.update_yaxes(autorange=False) # set auto range to false
28
# define the range of the y-axis using min and max functions
29
f.update_layout(yaxis_range=[df.values.min()-1, df.values.max()+1])
30
31
# create your traces from the data frame
32
for col in df.columns:
33
trace = go.Scatter(x=df.index, y=df[col], mode='lines+markers')
34
f.add_trace(trace)
35
36
# assign your functions to each trace
37
for trace in f.data:
38
trace.on_hover(hide_traces_on_hover)
39
trace.on_click(unhide_traces_on_click)
40
41
f
42
If you are running into issues, here is the jupyter notebook support documentation for using FigureWidget
and here is the jupyter lab support documentation. Make sure you have the ipywidgets
package installed. Also, just as a FYI, here is the FigureWidget documentation.
When you hover over a marker in the graph.
When you click on any marker of the visible trace all the hidden traces will become visible again.