Plotly Dash无法动态创建图表

5
我正在使用Plotly Dash创建一个Web应用程序来生成图表和处理回调。我使用的是dash-core-components v0.18.1。
当尝试动态添加图表(每次单击按钮时都会添加新图表)时,控制台中会出现错误:
bundle.js?v=0.11.2:9 Uncaught (in promise) Error: dash_core_components未找到。在Object.resolve(bundle.js?v = 0.11.2:9)中,在s(bundle.js?v = 0.11.2:9)中,在Array.map()中,在s(bundle.js?v = 0.11.2:9)中,在Array.map()中,在s(bundle.js?v = 0.11.2:9)中,在Array.map()中,在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中的一个错误吗?

嗨,我正在尝试做类似于这个的事情,即每当单选按钮被点击时渲染一个新图形,你能否指向一个完成此操作的示例的正确方向..或者你是如何学会自己完成它的?谢谢。 - JAbrams
请注意,此漏洞已在2018年11月修复(请参见此问题),因此不再需要采用所接受答案中的隐藏Div解决方法。 - Michel
1个回答

5
原来这是Dash中的一个缺陷。
解决方法:在加载时创建一个隐藏图形,如下所示:
app.layout = html.Div([
    html.Div(id='content'),
    dcc.Location(id='location', refresh=False),
    html.Div(dt.DataTable(rows=[{}]), style={‘display’: ‘none’})
])

原因是所需库仅在页面加载时加载,因此如果在加载时布局中没有图形,则某些Dash库将不会被加载。
更多信息可以在Dash问题板上找到: 这里这里

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接