繁体   English   中英

如何使用布尔开关更新 Dash 中的图形?

[英]How to use a boolean switch to update a graph in Dash?

我是 Dash 的新手。 我正在尝试使用daq.BooleanSwitch()类的输入来回调图形。 我可以显示一条消息,但我对图表有问题。

有没有人有任何可以帮助我的建议?

import dash
from dash.dependencies import Input, Output
import dash_daq as daq
import dash_html_components as html

app = dash.Dash(__name__)

app.layout = html.Div([

    html.H1("Here we go"),

    daq.BooleanSwitch(id='my_pb', on=False,color="red"),
    
    html.Div(id='power-button-result-1'),
    
    dcc.Graph(id="plot")

])

@app.callback(
    Output('power-button-result-1', 'children'),
    Input('my_pb', 'on')
)
def update_output(on):
    x = '{}'.format(on)
    if x == "True":
        return "Hi Iḿ using DASH"

@app.callback(
    Output('plot', 'figure'),
    Input('my_pb', 'on')
)
    
def figura(on):
    x = '{}'.format(on)
    if x == "True":
        # fig1 = Code to do a nice plot 
        return fig1

if __name__ == "__main__":             
    app.run_server(port = 1895)  
 

我的 DASH 输出如下所示:

在此处输入图片说明

我查看了您的代码,需要进行一些更改:

import dash
import dash_daq as daq

from dash import dcc
from dash import html

from dash.dependencies import Input
from dash.dependencies import Output


app = dash.Dash(__name__)

app.layout = html.Div(
    [
        html.H1("Here we go"),
        daq.BooleanSwitch(id="my_pb", on=False, color="red"),
        html.Div(id="power-button-result-1"),
    ]
)


@app.callback(
    Output("power-button-result-1", "children"),
    Input("my_pb", "on"),
)
def update_output(on):
    x = "{}".format(on)
    if x == "True":
        return [dcc.Graph(id="plot")]


if __name__ == "__main__":
    app.run_server(debug=True)

你非常接近 - 我认为你只需要一个回调。 在这里,您可以看到布尔开关现在切换dcc.Graph对象的显示(或不显示)。 这就是你要找的吗?

在此处输入图片说明

↓(拨动开关)

在此处输入图片说明

如果您希望图形已经被显示,然后在切换时更新,这里是上面相同代码的稍微修改的扩展版本来做到这一点:

import dash
import dash_daq as daq

from dash import dcc
from dash import html
from dash import no_update

from dash.dependencies import Input
from dash.dependencies import Output

import plotly.express as px
import pandas as pd


app = dash.Dash(__name__)

app.layout = html.Div(
    [
        html.H1("Here we go"),
        daq.BooleanSwitch(id="my_pb", on=False, color="red"),
        html.Div(
            [dcc.Graph(id="plot")], id="power-button-result-1"
        ),
    ]
)


@app.callback(
    Output("power-button-result-1", "children"),
    Input("my_pb", "on"),
)
def update_output(on):
    df = px.data.iris()
    if on:
        fig = px.scatter(df, x="sepal_width", y="sepal_length")
        dcc.Graph(figure=fig)
        return [dcc.Graph(figure=fig)]
    else:
        fig = px.scatter()
        return [dcc.Graph(figure=fig)]


if __name__ == "__main__":
    app.run_server(debug=True)

切换前 切换后

那里 - 好多了,希望有帮助?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM