简体   繁体   English

Python - /当我更改 Multi = True/Dash 组件和 Plotly 图表时,图表和下拉菜单之间的连接丢失

[英]Python - /Connections lost between graph and dropdown when i change Multi = True/Dash Components and Plotly Graphs

hope you are well., I'm quite new to Python.希望你很好。我对 Python 很陌生。 dash & Plotly and i am struggling to understand why i am unable to sync the dropdown bar with the graph its connected to.破折号和 Plotly 我很难理解为什么我无法将下拉栏与其连接的图形同步。

when Multi is at default the graph web page works fine however when i change the option its stops working.当 Multi 默认情况下,图形 web 页面工作正常,但是当我更改选项时,它停止工作。

if you are able to correct the code and provide some narrative to why my code doesnt work that would be much appreciated.如果您能够更正代码并提供一些说明为什么我的代码不起作用,那将不胜感激。

some narratives: in the excel sheet im uploading there is info on all states however i am only interested in 5 states in this example hence the dictionary containing 5 states一些叙述:在我上传的 excel 表中,有所有状态的信息,但是我只对这个例子中的 5 个状态感兴趣,因此字典包含 5 个状态

dff = dff[dff["state"] == option_selected] dff = dff [dff [“状态”] == option_selected]

the variable state here exists in the excel sheet thats in being imported into the data frame.此处的变量 state 存在于 excel 表中,该表正在导入数据框中。

also i am using this data set from covidtracking.com我也在使用来自 covidtracking.com 的数据集

thank you in advance!先感谢您!

import pandas as pd
import plotly.express as px  
import plotly.graph_objects as go
from dash import Dash, dcc, html, Input, Output  


app = Dash(__name__)

# -- Import and clean data (importing csv into pandas)

df = pd.read_csv("all-states-history.csv")

# ------------------------------------------------------------------------------
# App layout
app.layout = html.Div([

    html.H1("CV deaths by state", style={'text-align': 'center'}),

    dcc.Dropdown(id="slct_year",
                 options=[
                      {'label':'AZ','value': 'AZ'},
                      {'label':'CA','value': 'CA'},
                      {'label':'NY','value': 'NY'},
                      {'label':'FL','value': 'FL'},
                      {'label':'MA','value': 'MA'}],
                 multi=True,
                 #value=2015,
                 style={'width': "40%"}
                 ),

    html.Div(id='output_container', children=[]),
    html.Br(),

    dcc.Graph(id='my_map', figure={})

])


# ------------------------------------------------------------------------------
# Connect the Plotly graphs with Dash Components
@app.callback(
    [Output(component_id='output_container', component_property='children'),
     Output(component_id='my_map', component_property='figure')],
    [Input(component_id='slct_year', component_property='value')]
)
def update_graph(option_selected):
    print(option_selected)
    print(type(option_selected))

    container = "The state chosen by user was: {}".format(option_selected)

    dff = df.copy()
    dff = dff[dff["state"] == option_selected]


    # Plotly Express
    fig = px.choropleth(
        data_frame=dff,
        locationmode='USA-states',
        locations='state',
        scope="usa",
        color='state',
        hover_data=['state'],
        color_continuous_scale=px.colors.sequential.YlOrRd,
        
        template='plotly_dark'
    )


    return (container, fig)


# ------------------------------------------------------------------------------
if __name__ == '__main__':
    # For Development only, otherwise use gunicorn or uwsgi to launch, e.g.
    # gunicorn -b 0.0.0.0:8050 index:app.server
    app.run_server(
        port=8050,
        host='0.0.0.0'
    )

There are two issues I can see you'll run into: the first is that once the user selects from the dropdown, option_selected will be of type 'list' and the syntax for slicing a DataFrame based on whether an element is in a list is to use .isin .我可以看到您会遇到两个问题:第一个是,一旦用户从下拉列表中选择, option_selected将是'list'类型,并且根据元素是否在列表中切片 DataFrame 的语法是使用.isin

The other issue is that when the dash app is initialized option_selected will be NoneType because the user hasn't yet selected from the dropdown menu.另一个问题是,当 dash 应用程序初始化时option_selected将为NoneType因为用户尚未从下拉菜单中选择。 You can include a condition to check for that:您可以包含一个条件来检查:

if option_selected is not None:
    dff = dff[dff["state"].isin(option_selected)]

Then the dash app runs and you can select the 5 states.然后仪表板应用程序运行,您可以 select 5 个状态。

在此处输入图像描述

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

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