Filter/reduce scatter data with a slider

Hey all,

hope, you can help!

I am creating a bubble chart (scatter / plotly express) with just too many data in it. Therefore I would like to add a slider or range slider that is filtering the underlying data (the scatter is based on a dataframe).
The field I would like to use is the same field I use for the size of the bubbles.

Example would be: only show data points where the size value is >100.

Thanks for any hints or help!

I could also use “standard” plotly instead of ploty express. Even a dropdown would do it…

Best regards

Daniel

Hi @bluefrog ,

If you’re open to using Dash, here’s a working example using dcc.Rangeslider. You can insert your own data and alter the callback to create the plot as you see fit.

from dash import Dash, callback, Input, Output, State, html, dcc
import plotly.graph_objs as go
import pandas as pd
import numpy as np

# insert own data
data = pd.DataFrame(np.random.randint(0, 300, (10000, 3)))

app = Dash(__name__)

app.layout = html.Div([
    dcc.Graph(id='scatter-plot'),

    # change the slider range (this is what drives filtering)
    dcc.RangeSlider(0, 300, 10, value=[50, 80], id='slider'),
])


@callback(
    [Output('scatter-plot', 'figure')],
    [Input('slider', 'value')]
)
def update_plot(slider_range):
    # change the size column name to whatever it is for you
    size_col_name = 2

    data_filtered = data.where((data[size_col_name] > slider_range[0]) & (data[size_col_name] < slider_range[1])).dropna()

    # customize the figure
    fig = go.Figure(data=[go.Scatter(
        x=data_filtered[0], y=data_filtered[1],
        mode='markers',
        marker=dict(
            size=data_filtered[size_col_name],
        )
    )])

    return [fig]


if __name__ == '__main__':
    app.run(debug=True)

Hey 3d65,

thanks a lot for your answer!!.. just struggeling to get dash working with jupyter notebook or vs code… will run your example when solved that problem :slight_smile:

@bluefrog,

I haven’t used it myself, but using jupyter-dash might be a solution for you.

Got it working! Thank you so much! Do you think there is also a solution with Plotly/Python?