dash-docker-mwe icon indicating copy to clipboard operation
dash-docker-mwe copied to clipboard

working with bilerplate but error with my own dashboard

Open Shahin-rmz opened this issue 4 years ago • 2 comments

Hello, thanks for the boilerplate dash dock. we needed that. I am able to run the "hello " app. however, when I set the app to my custom code, I got the

gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> error.


here is the code

import dash
  1 from dash import dcc
  2 from dash import html
  3 import plotly.express as px
  4 import pandas as pd
  5 import pycountry
  6 import numpy as np
  7 from dash.dependencies import Input, Output
  8 from flask import Flask
  9
 10 #importing data from Kaggle data source as csv and change it to DataFrame
 11 map_csv = pd.read_csv("who_suicide_statistics.csv")
 12 df_map = pd.DataFrame(map_csv)
 13
 14 #Data refraction, some important countries(Iran and USA)
 15 input_countries = df_map['country']
 16
 17 countries = {}
 18 for country in pycountry.countries:
 19     countries[country.name] = country.alpha_3
 20
 21 country_codes = [countries.get(country, 'Unknown code') for country in input_countries]
 22 df_map['iso_data'] = country_codes
 23 df_map.loc[df_map.country=='Iran (Islamic Rep of)','iso_data']='IRN'
 24 df_map.loc[df_map.country=='United States of America','iso_data']='USA'
 25
 26 #making df3 which will be used for some Diagarams
 27 df3 = df_map.groupby(['country','iso_data','year'],as_index = False)['suicides_no','population'].sum()
 28 df3['proportion'] = df3['suicides_no']*1000/df3['population']
 29
 30 df3.replace([np.inf, -np.inf],np.nan,inplace=True)
 31 df3.dropna()
 32
 33 #also df4 is important for another diagram
 34 df4 = df3.loc[(df3!=0).any(axis=1)].dropna().sort_values(by='proportion')
 35
 36 #list of options for the dropdown
 37 options_list = [{'label': i, 'value': i} for i in df_map['country'].unique()]
 38 options_list.insert(0, {'label':'All','value':'All'})
 39
 40 #beginning of the dash
 41 server = Flask(__name__)
 42 app = dash.Dash(server=server)
 43 #making the layout
 44 app.title = 'LSMU Psychology'
 45 app.layout = html.Div([dcc.Markdown(''' # General statistics of international suicide phenomenon'''),
 46                        dcc.Markdown('''## map of the world'''),
 47                        dcc.Markdown('''In the choropleth map below you can see absolute number of suicide deaths by each of the country in our data set.
 48                                     please change the slider to see updated data for desired year.'''),
 49
 50                        dcc.Graph(id = "map_with_slider"),
 51
 52                        dcc.Slider(
 53                        id= 'year_slider',
 54                        min = map_csv['year'].min(),
 55                        max = map_csv['year'].max(),
 56                        value = map_csv['year'].min(),
 57                         marks = {str(year): str(year) for year in map_csv['year'].unique()},
 58                            tooltip={"placement": "bottom", "always_visible": True},
 59                        step = None
 60                        ),
 61                        dcc.Markdown('''## countries in comparison'''),
 62                        dcc.Markdown('''The left diagram shows the absolute count of suicide deaths in each country of the dataset and the right diagram shows relative number of suicide deaths in comparison to the population of the country.'''),
 63
 64                        html.Div([
 65                        dcc.Graph(id = "bar_chart")
 66                        ],style = {'width':'49%','display':'inline-block'}),
 67
 68                        html.Div([
 69                        dcc.Graph(id = "hbar_chart")
 70                        ],style = {'width':'49%','display':'inline-block'}),
 71
 72                        dcc.Markdown('''## One country under the focus'''),
 73                        dcc.Markdown('''Here you can focus on one country and check the suicide trends which have been seperated by Gender and  Age group.
 74                                     Here the suicide trends can be analyzed.'''),
 75                        html.Div([
 76                        dcc.Dropdown(id = 'country_picker', options =options_list ,value = 'Lithuania' )],style = {'width':'20%'}, title = 'please choose a country'),
 77                        dcc.Graph(id = 'one_country_chart'),
 78                        dcc.Markdown('''### Disclaimer: '''),
 79                        dcc.Markdown('''this project has been done by Ahmadreza Ramezanzadeh from group 49.
 80  #### Reference: '''),
 81                        dcc.Markdown('''[united nations Developlemnt program](http://hdr.undp.org/en/indicators/137506) 2018 Human Development index
 82                                     [kaggle] (https://www.kaggle.com/szamil/suicide-in-the-twenty-first-century/notebook) suicide in twenty first century
 83                                     [world health organization](http://www.who.int/mental_health/suicide-prevention/en/) suicide prevention''')
 84                        ])
 85 #the app contains two parts in ux first part give 3 results for the first part
 86 @app.callback(Output('map_with_slider','figure'),
 87               Output('bar_chart',"figure"),
 88               Output('hbar_chart','figure'),
 89               Input('year_slider','value'))
 90
 91 def update_figure(selected_year):
 92     #3 dataFrames for 3 diagrams
 93     filtered_df = df3[df3.year == selected_year]
 94     bar_df = df_map[df_map.year == selected_year]
 95     hbar_df = df4[df4.year == selected_year]
 96
 97     #choroplethe map
 98     fig = px.choropleth(filtered_df, locations = "iso_data",
 99                         color = "suicides_no",
100                         hover_name = "country",
101                         color_continuous_scale = px.colors.sequential.Plasma,
102                         title = 'Number of suicide deaths in {}, world view'.format(selected_year))
103     fig.update_geos(fitbounds="locations", visible=False)
104     fig.update_layout(transition_duration = 100)
105
106     #vertical bar chart
107
108     bar_fig = px.bar(bar_df,x='country',y = 'suicides_no',color = 'sex',title = 'Comparison of suicide deaths of each country in {}'.format(selected_year),hover_data = ['age'])
109     #Horizental bar chart
110     hbar_fig = px.bar(hbar_df,x= ('proportion'),y=('country'),orientation = 'h',title = 'Ranking of highest suicide mortality per capita in {}'.format(selected_year))
111     return fig,bar_fig,hbar_fig
112 #second part of the app
113 @app.callback(Output('one_country_chart', 'figure'),
114               Input('country_picker','value'))
115 def country_trend(selected_country):
116     country_df = df_map[df_map.country == selected_country]
117
118     country_fig = px.bar(country_df,x='year',y='suicides_no',color = 'sex', title = 'follow up of the suicide deaths in {} through years'.format(selected_country), hover_data = ['age'])
119
120     return country_fig
121
122 #server and render
123 if __name__ == '__main__':
124     app.run_server()
125

Shahin-rmz avatar Nov 13 '21 12:11 Shahin-rmz