情节图隐藏和显示

cev*_*zna 5 css python python-3.x plotly plotly-dash

我在 Python 框架 Dash 中隐藏和显示图形时遇到问题。我定义了一个新图:

html.Div([
  dcc.Graph(id = 'graph'),
 ],),
Run Code Online (Sandbox Code Playgroud)

在我使用回调函数更新我的跟踪数据后,我将其返回并显示在图表中,但如果我的下拉菜单中没有选择任何内容,我会这样做

if not input or input == []:
  return {'display': 'none'}
Run Code Online (Sandbox Code Playgroud)

所以我的图表没有显示,但由于某种原因它不起作用。有解决方法吗?

先感谢您

lwi*_*zek 8

您可以id为保持图形的 Div设置元素,并通过@app.callbackstyle元素上使用来隐藏整个 div 。

html.Div(id="graph-container", children= [
  dcc.Graph(id = 'graph'),
 ]),

@app.callback(Output('graph-container', 'style'), [Input('input_widget','value')])
def hide_graph(input):
    if input:
        return {'display':'block'}
    else:
        return {'display':'none'}
Run Code Online (Sandbox Code Playgroud)

要查看此代码的实际效果,您可以测试我的代码:

import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output

app = dash.Dash()

app.layout = html.Div(children=[
    html.H1(children='Hello Dash'),

    html.Div(children='''
        Dash: A web application framework for Python.
    '''),

    html.Label("Show?"),
    dcc.Dropdown(
        id="my-input",
        options = [
            {'label':'Yes', 'value':True},
            {'label':'No', 'value':False}
        ],
        value = True
    ),
    html.Div(
        id="graph-container", 
        children = [

        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'
            }
        }
    )
    ])


])

@app.callback(Output('graph-container', 'style'), [Input('my-input', 'value')])
def hide_graph(my_input):
    if my_input:
        return {'display':'block'}
    return {'display':'none'}



if __name__ == '__main__':
    app.run_server(port=8125, debug = True)
Run Code Online (Sandbox Code Playgroud)

注意我使用了以下版本:

  • 蟒蛇 3.6.4
  • 破折号 0.21.0
  • 直流电 0.22.1
  • html 0.10.0