Py.Cafe

petar-qb/

dash-clickData-vs-selectedData-on-graph-refresh

Interactive Iris Dataset Analysis with Click and Selection Feedback

DocsPricing
  • app.py
  • requirements.txt
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
import dash
import json
from dash import dcc, html, ctx
from dash.dependencies import Input, Output, State
import plotly.express as px
import pandas as pd

# Sample data
df = px.data.iris()

# Initialize the app
app = dash.Dash(__name__, suppress_callback_exceptions=True)

# Define the layout of the app
app.layout = html.Div(children=[
    html.H1(children='Dash App with a Graph and Filter'),

    # Dropdown filter
    dcc.Dropdown(
        id='variable-dropdown',
        options=["setosa", "virginica", "versicolor"],
        multi=False,
        value="setosa"
    ),

    html.Div([
        # Source interaction
        html.Div([
            dcc.Store(id="store_1", data=0),
            dcc.Graph(
                id="graph_1",
                figure=px.scatter(df, x="sepal_length", y="petal_length", color="species", custom_data="species", title="Source interaction refreshed 0 times"),
            ),
        ], style={"flex": "2"}),

        # JSON output container
        html.Div([
            html.H4("clickData Output"),
            html.Pre(id="json_clickData_output", style={
                "whiteSpace": "pre-wrap",
                "wordBreak": "break-word",
                "background": "#f8f8f8",
                "padding": "10px",
                "border": "1px solid #ccc",
                "borderRadius": "5px",
                "height": "300px",
                "overflowY": "scroll"
            })
        ], style={"flex": "1", "paddingLeft": "20px"}),

        html.Div([
            html.H4("selectedData Output"),
            html.Pre(id="json_selectedData_output", style={
                "whiteSpace": "pre-wrap",
                "wordBreak": "break-word",
                "background": "#f8f8f8",
                "padding": "10px",
                "border": "1px solid #ccc",
                "borderRadius": "5px",
                "height": "300px",
                "overflowY": "scroll"
            })
        ], style={"flex": "1", "paddingLeft": "20px"}),

    ], style={
        "display": "flex",
        "flexDirection": "row",
        "alignItems": "flex-start",
        "marginBottom": "30px"
    }),

    html.Div([
        # clickData target
        dcc.Store(id="store_2", data=0),
        dcc.Graph(
            id="graph_2",
            figure=px.scatter(df, x="sepal_length", y="petal_length", color="species", title="clickData target refreshed 0 times"),
        ),

        # selectedData target
        dcc.Store(id="store_3", data=0),
        dcc.Graph(
            id="graph_3",
            figure=px.scatter(df, x="sepal_length", y="petal_length", color="species", title="selectedData targetc refreshed 0 times"),
        )
    ],
    style={
        "display": "flex",
        "flexDirection": "row",
        "justifyContent": "space-between",
        "alignItems": "center"
    })
])


@app.callback(
    Output('graph_1', 'figure'),
    Output('store_1', 'data'),
    Input('variable-dropdown', 'value'),
    State('store_1', 'data'),
    prevent_callback_call=True,
)
def update_graph_1(selected_variable, store):
    if not ctx.triggered_id:
        raise dash.exceptions.PreventUpdate

    filtered_df = df[df['species'] == selected_variable]
    fig = px.scatter(filtered_df, x="sepal_length", y="petal_length", color="species", custom_data="species", title=f"Source interaction refreshed {store + 1} times")
    return fig, store + 1


@app.callback(
    Output('json_clickData_output', 'children'),
    Output('json_selectedData_output', 'children'),
    Input('graph_1', 'clickData'),
    Input('graph_1', 'selectedData'),
)
def display_click_selected_data(click_data, selected_data):
    return json.dumps(click_data, indent=2), json.dumps(selected_data, indent=2)


@app.callback(
    Output('graph_2', 'figure'),
    Output('store_2', 'data'),
    Input('graph_1', 'clickData'),
    State('store_2', 'data'),
    prevent_callback_call=True,
)
def update_graph_2(click_data, store):
    if not ctx.triggered_id:
        raise dash.exceptions.PreventUpdate

    if click_data:
        clicked_point = click_data['points'][0]['customdata'][0]
        filtered_df = df[df['species'].isin([clicked_point])]
    else:
        filtered_df = df

    fig = px.scatter(filtered_df, x="sepal_width", y="petal_width", color="species", title=f"clickData target refreshed {store + 1} times")
    return fig, store + 1


@app.callback(
    Output('graph_3', 'figure'),
    Output('store_3', 'data'),
    Input('graph_1', 'selectedData'),
    State('store_3', 'data'),
    prevent_callback_call=True,
)
def update_graph_2(selected_data, store):
    if not ctx.triggered_id:
        raise dash.exceptions.PreventUpdate

    if selected_data:
        selected_points = [point['customdata'][0] for point in selected_data['points']]
        filtered_df = df[df['species'].isin(selected_points)]
    else:
        filtered_df = df

    fig = px.scatter(filtered_df, x="sepal_width", y="petal_width", color="species", title=f"selectedData target refreshed {store + 1} times")
    return fig, store + 1


# Run the app
app.run(debug=True)