Eli*_*ion 3 python plotly plotly-dash
我正在阅读一些教程,包括官方文档,似乎每个人都更Output
喜欢figure
.
例如:
@app.callback(
Output('graph-with-slider', 'figure'),
Input('year-slider', 'value'))
def update_figure(selected_year):
filtered_df = df[df.year == selected_year]
fig = px.scatter(filtered_df, x="gdpPercap", y="lifeExp",
size="pop", color="continent", hover_name="country",
log_x=True, size_max=55)
fig.update_layout(transition_duration=500)
return fig
Run Code Online (Sandbox Code Playgroud)
为什么不只将数据输出到data
图形字段呢?
是否可以?
小智 6
您可以使用仅返回数据和布局等的回调
app.layout = html.Div([
dcc.Dropdown(
id='my_input',
value='A',
options=[{'label': i, 'value': i} for i in ["value_1","value_2"]]
),
dcc.Graph(id='my_graph')
])
@app.callback(Output('my_graph', 'figure'),
Input('my_input', 'value'))
def update_live_graph(value):
data = get_data() #assuming dataframe/dict for simplicity
return {
'data': [{
'x': data['x'],
'y': data['y'],
'line': {...} # line properties, could also be marker={...}
}],
'layout': {
# aesthetic options
'margin': {'l': 40, 'b': 40, 'r': 20, 't': 10},
'xaxis': {'showgrid': False, 'zeroline': False},
'yaxis': {'showgrid': False, 'zeroline': False}
}
}
Run Code Online (Sandbox Code Playgroud)
但返回数字通常比这更简洁,更容易理解,并且更不容易出错