首页 > 解决方案 > Plotly Dash - 在 dcc.graph 中向图形添加标题时出现语法错误

问题描述

刚刚浏览了 Dash 网站上的示例教程,我尝试修改示例代码,并在尝试为第二个 dcc.Graph 中的图形添加标题时遇到语法错误。

第二个 dcc.Graph 是我创建的。 代码调试器报告“标题”和“测试进度”之间的冒号是语法错误。我检查了所有的括号,它们都正确排列。请注意,我没有包含完整的源代码,因为只有 dcc.Graph 部分与错误相关。我的猜测是可能使用了错误类型的括号。但基于第一个 dcc.Graph,我认为情况并非如此。

dcc.Graph(
            id='example-graph',
            figure={
                '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'
                }
            }
        ),
dcc.Graph(id='plot1', 
                  figure={          
                plotly_figure, 'layout' : {
                    'title': 'Test Progress'
                    }

                }
            )

附加信息:在 dcc.Graph 部分添加了与 plotly_figure 相关的实际数据行,并且不再出现语法错误。

plotly_figure = dict(data=[dict(x=[1,2,3], y=[2,4,8])])

dcc.Graph(id='plot1', 
                  figure = {          
                          'data': [
                    {dict(data=[dict(x=[1,2,3], y=[2,4,8])])},
                ],
                          'layout' : {
                        'title' : 'Test Progress'
                    }

                }
            )

问题的解决方案:plotly_fig 的正确语法如下:

plotly_fig = [dict(x=[1,2,3], y=[2,4,8])]
dcc.Graph(id='plot1', 
                      figure={          
                    plotly_fig, 'layout' : {
                        'title': 'Test Progress'
                        }

                    }
                )

标签: pythonplotlyplotly-dash

解决方案


推荐阅读