Way to get current state of hidden/non-hidden traces on a plotly graph (Python3, Plotly.graph_objs)

Viewed 207

I am using the the Python3 version of plotly.graph_objs as well as ipywidgets to create an interactive graph. My data has multiple columns that can be selected from a dropdown. I NEED to use the ipywidget interactive output to accomplish this.

The full data has about 20 traces which I want the user to be able to disable by clicking on the plotly legend element associated with that trace. There will also be other ipywidgets to filter the data with.

Any time a filter is changed, the plot seems to be redrawn. The problem with this is that the state of which traces were hidden is lost. I.e. if I hide trace 1, then update the column dropdown, all plots are visible again once the data is updated.

Is there a way to get the state of which traces are hidden/visible from plotly? Is there an event listener I can get access to to call a function when a trace is disabled? I know I can set the visibility of a trace myself in a function, but I have not been able to find a way of getting the current state before updating a dropdown.

Code:

import random
import plotly.graph_objs as go
from  plotly.offline import *
init_notebook_mode(connected=False)
import ipywidgets as widgets

cols = ['col1', 'col2']
y1 = [random.randrange(1, 100, 1) for i in range(100)]
y2 = [random.randrange(1, 100, 1) for i in range(100)]
y3 = [random.randrange(1, 100, 1) for i in range(100)]
x = [i for i in range(0,20)]

g = {}

col_widget = widgets.Dropdown(options = cols, description='Column', continuous_update=False)

def update_col(change):
    pass

col_widget.observe(update_col, names='value')

def plot_graph(col):
    global g
    traces = []
    
    trace1 = go.Scatter(
                x = x,
                y = y1,
                mode = 'lines',
                visible = True
            )

    traces.append(trace1)
    
    trace2 = go.Scatter(
                x = x,
                y = y2,
                mode = 'lines',
                visible = True
            )

    traces.append(trace2)
    
    trace3 = go.Scatter(
                x = x,
                y = y3,
                mode = 'lines',
                visible = True
            )

    traces.append(trace3)

    g = dict(data = traces)
    iplot(g)

out = widgets.interactive_output(plot_graph, {'col' : col_widget})
display(col_widget, out)

In separate cell:

g['data'][0]

^This lets you see the data associated with the first trace. It does not change when you disable a trace in the plot.

0 Answers
Related