【问题标题】:Dash Plotly: Highlighting point on the graphDash Plotly:图表上的高亮点
【发布时间】:2019-10-26 00:11:06
【问题描述】:

我正在谷歌搜索,试图找到以下问题的解决方案(到目前为止还没有运气)。我正在使用 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

现在,我想要另一个回调,它会根据某些输入条件突出显示图表上的特定点(或添加/删除点)。在这种情况下,我很难弄清楚输出要使用什么?因为我不能再次输出 graph.figure (Dash 不允许从不同的回调输出到同一个组件)。并且重新绘制整个图表似乎效率低下。

我将不胜感激任何建议。

【问题讨论】:

  • 也许您可以在同一个回调中添加另一个输入并处理回调中的逻辑?
  • @run-out 说得通。谢谢。

标签: plotly-dash


【解决方案1】:

使用这个库可以在不重绘整个图表的情况下更改图表的布局: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)

【讨论】:

  • 太酷了!我会尝试。这可能对其他事情也有帮助。
猜你喜欢
  • 2021-08-26
  • 2021-11-04
  • 1970-01-01
  • 1970-01-01
  • 2020-03-07
  • 1970-01-01
  • 1970-01-01
  • 2018-11-11
  • 2021-10-28
相关资源
最近更新 更多