我正在努力寻找以下问题的解决方案(到目前为止没有运气)。我正在使用Plotly Dash回调来建立图形:
@app.callback(
Output("graph", "figure"),
[Input("some-input", "value")],
[State("some-state", "value")])
def build_graph(input_value, state_value):
// computing data for graph_figure
return graph_figure
现在,我想要另一个回调,该回调将根据某些输入条件突出显示图形上的特定点(或添加/删除点)。我很难弄清楚在这种情况下对Output使用什么?因为我无法再次输出graph.figure(Dash不允许从不同的回调输出到同一组件)。重新绘制整个图似乎效率很低。
我将不胜感激任何建议。
答案 0 :(得分:0)
可以使用以下https://github.com/jimmybow/mydcc
来更改图形的布局而无需重绘整个图形。这里有一个使用示例:https://github.com/jimmybow/mydcc#3-mydccrelayout-
我准备了一个小示例,在单击按钮时添加了注释。不要忘记事先pip install mydcc
。我必须添加一个缓存(以不可见的div形式)以在添加新注释时保留旧注释。
import dash
import dash_core_components as dcc
import dash_html_components as html
import mydcc
import random
import json
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
initial_layout = {'title': 'Dash Data Visualization'}
app.layout = html.Div(children=[
html.H1(children='Hello Dash'),
html.Div(children='''
Dash: A web application framework for Python.
'''),
dcc.Graph(
id='example-graph',
figure={
'data': [{'x': [1, 2, 3], 'y': [4, 1, 2], 'name': 'Test'}],
'layout': initial_layout
}
),
mydcc.Relayout(id="rrr", aim='example-graph'),
html.Button('Add random annotation', id='button'),
html.Div(id='user-cache', style={'display': 'none'},
children=json.dumps(initial_layout)),
])
@app.callback(
[dash.dependencies.Output('rrr', 'layout'),
dash.dependencies.Output('user-cache', 'children')],
[dash.dependencies.Input('button', 'n_clicks')],
[dash.dependencies.State('user-cache', 'children')])
def update_graph_annotations(n_clicks, layout):
if n_clicks is not None:
layout = json.loads(layout)
if not 'annotations' in layout:
layout['annotations'] = []
layout['annotations'].append(dict(
x=random.uniform(0, 1) * 2 + 1,
y=random.uniform(0, 1) * 2 + 1,
xref="x",
yref="y",
text="Annotation" + str(n_clicks),
showarrow=True
))
return layout, json.dumps(layout)
return dash.no_update, dash.no_update
if __name__ == '__main__':
app.run_server(debug=True)