I am trying to run the basic Crossfiltering tutorial found here Part 4. Interactive Graphing and Crossfiltering | Dash for Python Documentation | Plotly (under Generic Crossfilter Recipe) and am struggling to get it working.
I am encountering two problems:
(1) The following two lines are seen as a syntax error in my Python 3 implementation:
if selectedpoints_local and selectedpoints_local['range']:
if selected_data and selected_data['points']:
When they are run the first time, because both variables selectedpoints_local and selected_data are “None” and thus don’t have a ‘range’ or a ‘points’ key, which causes Python to crash.
(2) I tried fixing this problem with “Try” and “Except” statements, but I am ending up with a functional user interface, except that every time I make a selection, the callback is triggered twice, once with the correct selection, and a second time with an empty selection, causing the graph to refresh with an empty selection. I am really stumped here, and have tried to gradually remove everything from the code to understand why the callback gets triggered twice systematically.
Even this really simplified version of the tutorial shows this problem, where the callback gets triggered twice with a single selection:
from dash import Dash, dcc, html
import numpy as np
import pandas as pd
from dash.dependencies import Input, Output
import plotly.express as px
app = Dash(__name__)
# make a sample data frame with 2 columns
np.random.seed(0) # no-display
df = pd.DataFrame({"Col " + str(i+1): np.random.rand(30) for i in range(2)})
app.layout = html.Div([
dcc.Graph(id='g1')
])
def get_figure(df, x_col, y_col):
fig = px.scatter(df, x=x_col, y=y_col)
return fig
@app.callback(
Output('g1','figure'),
Input('g1', 'selectedData')
)
def callback(selection1):
print("CALLBACK")
return get_figure(df, "Col 1", "Col 2")
if __name__ == '__main__':
app.run_server(debug=True)
I am under the impression something is wrong with the syntax of the callback in the tutorial, but being unfamiliar with plotly, I have not been able to fix this.
Any help would be greatly appreciated.