Noa Be
Noa Be

Reputation: 337

Create a Plotly button to hide/show data points in ScatterPlot

I have a large scatter plot displayed, and now I want to make my user able to filter out some points with a few buttons

for example, let's say points is an array

Is there a simple way to achieve this ? I've been searching on internet for so long...

I know the code below should work, but I can't find the right args :/ I want to use a boolean array saying whether or not the point should be displayed

fig.update_layout(
    updatemenus=[
        dict(
            type="buttons",
            buttons=[
                dict(method='restyle',
                        label=col,
                        visible=True,
                        args=< ??? >,
                        ),
            ],
        )
    ]
)

Upvotes: 3

Views: 1427

Answers (1)

Derek O
Derek O

Reputation: 19590

I think passing a dictionary such as args={'visible': [True, False]} is what you are looking for. A button with these settings would show the first trace and hide the second trace, so this will work as long as you create your scatterplot using multiple traces. For example:

import pandas as pd
import plotly.graph_objects as go

fig = go.Figure()
fig.add_trace(go.Scatter(
    x=[1,2,2],
    y=[4,5,4],
    mode='markers',
    name='cluster 1',
    marker=dict(color="red")
))

fig.add_trace(go.Scatter(
    x=[7,8,7],
    y=[3,4,2],
    mode='markers',
    name='cluster 2',
    marker=dict(color="blue")
))

fig.update_layout(
    updatemenus=[
        dict(
         buttons=list([   
            dict(label = 'show cluster 1',
                 method = 'update',
                 args = [{'visible': [True, False]},
                         {'title': 'cluster 1'}]),

            dict(label = 'show cluster 2',
                 method = 'update',
                 args = [{'visible': [False, True]},
                         {'title': 'cluster 2'}]),
            
            dict(label = 'show both clusters',
                 method = 'update',
                 args = [{'visible': [True, True]},
                         {'title': 'cluster 2'}])
        ]),
    )]
)

fig.update_xaxes(range=[0, 10])
fig.update_yaxes(range=[0, 10])
fig.show()

enter image description here

Upvotes: 3

Related Questions