我正在学习dash库。这段代码显示了当我在数据框中选择列时的散点图。这工作没有任何问题,但回调错误发生在网页上。
在网络上,更新spas-graph.figure时出现回调错误我不明白为什么会出现这个错误。
[import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.graph_objects as go
import pandas as pd
df = pd.DataFrame({
'depth' : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'upper_value' : [1, 4, 6, 2, 6, 8, 9, 10, 4, 2],
'middle_value' : [5, 3, 7, 8, 1, 2, 3, 1, 4, 8],
'down_value' : [6, 2, 1, 10, 5, 2, 3, 4, 2, 7]
})
col_list = df.columns[1:4]
app = dash.Dash(__name__)
app.layout = html.Div([
dcc.Dropdown(
id = 'select-cd',
options = [
{'label' : i, 'value' : i}
for i in col_list
]
),
dcc.Graph(id = 'spas-graph')
])
@app.callback(
Output('spas-graph', 'figure'),
[Input('select-cd', 'value')]
)
def update_figure(selected_col):
return {
'data' : [go.Scatter(
x = df[selected_col],
y = df['depth'],
mode = 'lines + markers',
marker = {
'size' : 15,
'opacity' : 0.5,
'line' : {'width' : 0.5, 'color' : 'white'}
}
)],
'layout' : go.Layout(
xaxis={'title': 'x_scale'},
yaxis={'title': 'y_scale'},
hovermode='closest'
)
}
if __name__ == '__main__':
app.run_server(debug=True)
您尚未在下拉方法中定义值参数。因此,当服务器启动时,它接收到的第一个输入是None值。
你可以用两种方法来解决它:
-
在下拉菜单中添加默认值:
-
回调方法中的Handle None值
import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output import plotly.graph_objects as go import pandas as pd df = pd.DataFrame({ 'depth' : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 'upper_value' : [1, 4, 6, 2, 6, 8, 9, 10, 4, 2], 'middle_value' : [5, 3, 7, 8, 1, 2, 3, 1, 4, 8], 'down_value' : [6, 2, 1, 10, 5, 2, 3, 4, 2, 7] }) col_list = df.columns[1:4] app = dash.Dash(__name__) app.layout = html.Div([ dcc.Dropdown( id = 'select-cd', options = [ {'label' : i, 'value' : i} for i in col_list ], value = col_list[0] ), dcc.Graph(id = 'spas-graph') ]) @app.callback( Output('spas-graph', 'figure'), [Input('select-cd', 'value')] ) def update_figure(selected_col): if selected_col is None: selected_col = col_list[0] return { 'data' : [go.Scatter( x = df[selected_col], y = df['depth'], mode = 'lines + markers', marker = { 'size' : 15, 'opacity' : 0.5, 'line' : {'width' : 0.5, 'color' : 'white'} } )], 'layout' : go.Layout( xaxis={'title': 'x_scale'}, yaxis={'title': 'y_scale'}, hovermode='closest' ) }