Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

plotly

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

  • button_1 : show only points[[1,2,3]]
  • button_2 : show only points[[4,5,6]]

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=< ??? >,
                        ),
            ],
        )
    ]
)
like image 505
Noa Be Avatar asked May 18 '26 12:05

Noa Be


1 Answers

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

like image 55
Derek O Avatar answered May 21 '26 02:05

Derek O



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!