【问题标题】:Plotly Dash Cannot Create Graphs DynamicallyPlotly Dash 无法动态创建图形
【发布时间】:2018-02-20 13:34:49
【问题描述】:

我正在使用 plotly dash 创建一个 Web 应用程序,用于图形生成和回调处理。我使用 dash-core-components v0.18.1

尝试动态添加图表时(每次单击按钮时,都会添加一个新图表),控制台中会出现错误:

bundle.js?v=0.11.2:9 Uncaught (in promise) 错误:dash_core_components 没找到。在 Object.resolve (bundle.js?v=0.11.2:9) 在 s (bundle.js?v=0.11.2:9) at Array.map () at s (bundle.js?v=0.11.2:9) at Array.map() at s (bundle.js?v=0.11.2:9) at Array.map() at s (bundle.js?v=0.11.2:9) 在 e.value (bundle.js?v=0.11.2:9) 在 p._renderValidatedComponentWithoutOwnerOrContext (react-dom@15.4.2.min.js?v=0.11.2:13)

我只有一个带有按钮和点击回调的空白页面。 回调只是用图表填充 div。

布局代码:

class ContentController(object):

    graph_names = None

    def __init__(self):
        self.graph_names = []
        # UNCOMMENT THIS LINE TO MAKE IT WORK
        # self.graph_names = ["start_graph"]

    def layout(self):
        return html.Div([html.Button("Add Graph", id='button_id'),
                         html.Div(self.graphics_layout, id='graphics_div')],
                        id='main_div')

    @property
    def graphics_layout(self):
        graphs = []
        for name in self.graph_names:
            graph = self.create_graph()
            graphs.append(dcc.Graph(id=name, figure=graph, style=    {'width': '600px', 'height': '300px'}))

        return graphs

    def create_graph(self):
        graph_data = {
               'data': [
                   {'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar',     'name': 'SF'},
                   {'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar',     'name': u'Montréal'},
               ],
               'layout': {
                   'title': 'Dash Data Visualization'
               }
           }
        return graph_data

回调代码

@app.callback(
    Output(component_id='graphics_div', component_property='children'),
    [Input(component_id='button_id', component_property='n_clicks')]
)
def callback_function(n_clicks):
    print(n_clicks)
    if n_clicks is None:
        return ""

    name = "graph_" + str(n_clicks)
    content.graph_names.append(name)
    return content.graphics_layout

奇怪的是,如果在加载页面时出现另一个图表,那么一切正常。这是 Dash 中的错误吗?

【问题讨论】:

  • 嗨,我正在尝试做与此类似的事情,因为我想在单击单选按钮时呈现一个新图形,你能指出我正确的方向吗?完成..或者你是如何学会自己做的?谢谢
  • 请注意,此缺陷已于 2018 年 11 月修复(请参阅 this issue),因此不再需要已接受答案中隐藏的 Div 解决方法。

标签: python plotly plotly-dash


【解决方案1】:

事实证明这是 Dash 的一个缺陷。

解决方法:在加载时创建一个隐藏图,如下所示:

app.layout = html.Div([
    html.Div(id='content'),
    dcc.Location(id='location', refresh=False),
    html.Div(dt.DataTable(rows=[{}]), style={‘display’: ‘none’})
])

原因是需要的库只在页面加载时加载,所以如果加载时布局中没有图表,一些dash库将不会加载。

更多信息可以在破折号问题板上找到: HereHere

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-04
    • 1970-01-01
    • 2020-08-25
    • 1970-01-01
    • 2021-09-08
    • 2020-03-30
    • 2020-09-27
    • 1970-01-01
    相关资源
    最近更新 更多