破折号无法工作(下拉和条形图)

Dash unable to work (Dropdown and bar chart)

我似乎无法制作仪表板,主要问题出在下拉列表和图表(条形图)中。我已经尝试了大部分的东西,但我仍然无法弄清楚问题是什么。有谁知道我的代码有什么问题? 'population' 基本上就是 'native country'.

我在这里上传了我的数据: https://github.com/standatagithub/cpsdata/blob/main/cpsdata.csv

这是我的代码:

import dash
from jupyter_dash import JupyterDash  # pip install dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import plotly.graph_objs as go
from dash.dependencies import Input, Output

df = pd.read_csv(r'C:\Users\mrsta\OneDrive\Desktop\cpsdata.csv')

app = JupyterDash()


#AppLayout
app.layout = html.Div([
    
            html.H1("Population in a city", style={'text-align': 'center'}),
    
            dcc.Dropdown(
                id='population-dropdown',
                options=[{'label': i, 'value': i} for i in list(df.Native_Country_of_Father.unique())],
                placeholder="Please select..",
                searchable=True
            ),
           
            dcc.Slider(
                id='year-slider',
                min=df['Year'].min(),
                max=df['Year'].max(),
                value=df['Year'].min(),
                step=None,
                marks={str(Year): str(Year) for Year in df['Year'].unique()}
            ),
    
            dcc.Graph(id='graph-with-slider'),
            
     
        ],
        style={'width': '48%', 'display': 'inline-block'})


#App CallBack

@app.callback(
    Output('graph-with-slider', 'figure'),
    [Input('year-slider', 'value'),
     Input('population-dropdown','value')])

#Figure Update

def update_figure(selected_year, selected_population):
    filtered_df = df[df['Native_Country_of_Father']] == selected_population
    filtered_df = filtered_df[filtered_df.Year == selected_year]
    traces = []
    for i in df.Native_Country_of_Father.unique():
        df_by_population = filtered_df[filtered_df['selected_population'] == i]
        traces.append(go.Bar(
             x=df_by_population['City'],
             y=df_by_population['Native_Country_of_Father'], #Numberofpopulation
             text=df_by_continent['City'],
             barmode='stack'),
            name=i
        )
                     
    return {
        'data': traces,
        'layout': go.Layout(
            margin={'l': 40, 'b': 40, 't': 10, 'r': 10},
            legend={'x': 0, 'y': 1},
            hovermode='closest'
        )
    }


if __name__ =='__main__':
    app.run_server(mode="external")

这是我的数据帧和我收到的错误信息:

扩展了第一条错误消息

扩展了第二个错误消息

我认为我的输出应该是这样的。我从多个来源裁剪和编辑了这张图片。

有多种因素阻止了它的工作。首先是下拉菜单不会出现。原因是数据中含有nan,需要去掉。删除的结果列表是 dd_list。接下来,滑块更改为范围滑块。默认值是年份的最小值和最小值加 1。这里是 2005 年。接下来,由于我们循环遍历图形而不是一次绘制所有数据,因此我们绘制过滤后的数据帧。条形图类型是分组的,但是预期的输出不是分组模式,所以禁用了。图更新函数的 return 被重写为 fig only。通过更改滑块右侧的值来更新图形。 selected_yaer1是右边的值。制定此规范是为了了解滑块的 return 值。如果按原样使用滑块,则需要修改代码,因为条件是滑块必须大于或等于开始年份且小于或等于结束值。如果年份选择是单个年份,则需要将其更改为 drop-down 或单选按钮。

import dash
from jupyter_dash import JupyterDash
from dash import html
from dash import dcc
import pandas as pd
import plotly.graph_objs as go
from dash.dependencies import Input, Output

url = 'https://raw.githubusercontent.com/standatagithub/cpsdata/main/cpsdata.csv'
df = pd.read_csv(url, sep=',')
dd_list = df.Native_Country_of_Father.dropna().unique()

app = JupyterDash()

#AppLayout
app.layout = html.Div([
    
            html.H1("Population in a city", style={'text-align': 'center'}),
    
            dcc.Dropdown(
                id='population-dropdown',
                options=[{'label': i, 'value': i} for i in dd_list],
                placeholder="Please select..",
                #value='United States',
                searchable=True
            ),
           
            dcc.RangeSlider(
                id='year-slider',
                min=df['Year'].min(),
                max=df['Year'].max(),
                value=[df['Year'].min(),df['Year'].min()+1],
                step=1,
                marks={str(Year): str(Year) for Year in df['Year'].unique()}
            ),
    
            dcc.Graph(id='graph-with-slider'),
            
     
        ],
        style={'width': '100%', 'display': 'inline-block'})


#App CallBack
@app.callback(
    Output('graph-with-slider', 'figure'),
    [Input('year-slider', 'value'),
     Input('population-dropdown','value')])

#Figure Update
def update_figure(selected_year, selected_population):
    print(selected_year, selected_population)
    filtered_df = df[df['Native_Country_of_Father'] == selected_population]
    filtered_df = filtered_df[filtered_df.Year == selected_year[1]]
    filtered_df = filtered_df.groupby('City').count().reset_index()
    print(filtered_df.head())
    traces = []
    #for i in dd_list:
    #    df_by_population = filtered_df[filtered_df['Native_Country_of_Father'] == i]
        #traces.append(
            #name=i
    fig = go.Figure(go.Bar(
        x=filtered_df['City'],
        y=filtered_df['Native_Country_of_Father'], #Numberofpopulation
        text=filtered_df['City'],
        #barmode='stack'
    ))
    fig.update_layout(
        margin={'l': 40, 'b': 40, 't': 10, 'r': 10},
        legend={'x': 0, 'y': 1},
        hovermode='closest'
    )  
                     
    return fig

if __name__ =='__main__':
    app.run_server(debug=True, mode="inline")