pythonplotlyplotly-dashfigure

Python Plotly Express Line Graph remvoe selection box after using figure.add_selection


So, I have this app in which i create a figure using plotly.express.line and then I use the add_selection() function like that : figure.add_selection( x0=0, y0=10, x1=10, y1=0 ) which indeed adds a selection box. But, the issue is that I want to remove this selection box by script. I tried a lot of things like figure.update_layout(dragmode='zoom') but even this doesn't remove the selection box. Is there any functions like figure.clear_selection() or something like that ? Thanks a lot :)


Solution

  • Putting together a working example of the comment by @SquidyDev on his question above.

    The top portion of the code adds Squidy's custom function 'clear_selection' to the definition of a plotly go.Figure, which can then be called inside the loop to clear the previous selection.

    import numpy as np
    from plotly import graph_objects as go
    
    
    def clear_selection(self):
        """
        Custom function for cleaning selections from Plotly Figure
    
        """
        if 'selections' in self['layout']:
            self['layout']['selections'] = ()
    
    
    go.Figure.clear_selection = clear_selection
    
    # Normal plot, adding selection and looping through for user to interact with selection
    t = np.linspace(0, 4*np.pi)
    fig = go.Figure()
    fig.add_scatter(
        x=t,
        y=np.sin(t),
    )
    
    for ii in range(5):
        fig.clear_selection()
        fig.add_selection(
            x0=ii, y0=-0.5,
            x1=ii+1, y1=0.75
        )
        fig.show()
        breakpoint()