0

I am trying to create a dashboard to show the ethnicity makeup in different cities for multiple years. My dataframe consists of Year, Month, City and Native variables. I pasted an image on the bottom that shows my dataframe. I also tried to replicate a Dash code that I have but I received multiple errors after executing it, and it looks like most of the errors are about the City variable. Is there any guide to get my dash to work?

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

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 

app = JupyterDash()

app.layout = html.Div([
            html.H1("Native Country of Father"), 
            dcc.Dropdown(
                id='cities',
                options=[{'label': i, 'value': i} for i in list(df.City.unique()) + ['All']],
                value='All'
            ),
            dcc.RadioItems(
                    id='xaxis-type',
                    options=[{'label': i, 'value': i} for i in ['Linear', 'Log']],
                    value='Log',
                    labelStyle={'display': 'inline-block'}
                ),    
            dcc.Graph(id='graph-with-slider'),
            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()}
            )
            
        ],
        style={'width': '48%', 'display': 'inline-block'})


@app.callback(
    Output('graph-with-slider', 'figure'),
    [Input('year-slider', 'value'),
     Input('xaxis-type','value'),
     Input('cities','value')])

def update_figure(selected_year, axis_type, City):
    if City=="All":
        filtered_df = df
    else:
        filtered_df = df[df['City']==City]
    filtered_df = filtered_df[filtered_df.Year == selected_year]
    traces = []
    for i in filtered_df.City.unique():
        df_by_City = filtered_df[filtered_df['City'] == i]
        traces.append(go.Scatter(
            y=df_by_City['Native Country of Father'],
            text=df_by_City['Native Country of Father'],
            mode='markers',
            opacity=0.7,
            marker={
                'size': 15,
                'line': {'width': 0.5, 'color': 'white'}
            },
            name=i
        ))

    return {
        'data': traces,
        'layout': go.Layout(
            xaxis={'type': 'linear' if axis_type == 'Linear' else 'log',
                   'title': 'GDP Per Capita'},
            yaxis={'title': 'Life Expectancy', 'range': [20, 90]},
            margin={'l': 40, 'b': 40, 't': 10, 'r': 10},
            legend={'x': 0, 'y': 1},
            hovermode='closest'
        )
    }


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

enter image description here

enter image description here

enter image description here

enter image description here

dspassion
  • 41
  • 1
  • 7
  • I have the city name in the input element dropdown, the year selected in the slider, and the x-axis set in the radio button, but is it all aligned in the callback function? – r-beginners May 01 '22 at 06:50
  • Those errors should all be self-explanatory. Expand them and read the full details. I can already see, based on the first one, that your `['All']` is incorrect for the dropdown. It needs to be a dict with a label and value. – coralvanda May 01 '22 at 14:29
  • @r-beginners Yes I believe it is aligned in the callback function. – dspassion May 01 '22 at 17:18
  • @coralvanda do I just make a dictionary of {City: a, b, c.....} ? – dspassion May 01 '22 at 17:38

1 Answers1

-1

To get the dropdown working properly, you'll have to fix the value passed to options. What you have is:

options=[{'label': i, 'value': i} for i in list(df.City.unique()) + ['All']]

If you remove ['All'] and change the value prop, it should work. In order to have a value that selects everything, you need something like

options=[
    {'label': i, 'value': i} for i in list(df.City.unique()) 
] + [{'label': 'All', 'value': 'All'}]
coralvanda
  • 6,431
  • 2
  • 15
  • 25
  • Hi, I just tried this but it is still giving me the same result. I am still receiving this error message "Invalid argument `options` passed into Dropdown with ID "cities"." – dspassion May 02 '22 at 04:28
  • Wondering if it's because I have too many cities in the variable? There are probably like around 50-100 cities. – dspassion May 02 '22 at 05:07
  • No, it can handle that many. Does it show the full value provided? It's likely the very last entry that's an issue. Can you edit your question to show that? – coralvanda May 02 '22 at 23:44
  • hey I actually started another thread with a detailed information. Would you mind checking that out? – dspassion May 03 '22 at 00:29
  • https://stackoverflow.com/questions/72093071/dash-unable-to-work-dropdown-and-bar-chart – dspassion May 03 '22 at 01:29
  • I still need to see what the last part of the error related to the `options` says. Can you show that? – coralvanda May 03 '22 at 01:32