...
/Incorporating the Functionality into the App
Incorporating the Functionality into the App
Learn how to add bar charts and drop-down components to a Dash application.
We'll cover the following...
We are now ready to add the new functionality to our app again using the function and chart we just created. At this stage, not much explanation is required since we’ve done this enough times. But we’ll go through the main steps, and we can always refer to the code repository to check our work.
import reincome_share_df = poverty.filter(regex='Country Name|^year$|Income share.*?20').dropna()income_share_df = income_share_df.rename(columns={'Income share held by lowest 20%': '1 Income share held by lowest 20%','Income share held by second 20%': '2 Income share held by second 20%','Income share held by third 20%': '3 Income share held by third 20%','Income share held by fourth 20%': '4 Income share held by fourth 20%','Income share held by highest 20%': '5 Income share held by highest 20%'}).sort_index(axis=1)income_share_df.columns = [re.sub('\d Income share held by ', '', col).title()for col in income_share_df.columns]income_share_cols = income_share_df.columns[:-2]income_share_dfdcc.Dropdown(id='income_share_country_dropdown',options=[{'label': country, 'value': country}for country in income_share_df['Country Name'].unique()]),dcc.Graph(id='income_share_country_barchart')@app.callback(Output('income_share_country_barchart', 'figure'),Input('income_share_country_dropdown', 'value'))def plot_income_share_barchart(country):if country is None:raise PreventUpdatefig = px.bar(income_share_df[income_share_df['Country Name']==country].dropna(),x=income_share_cols,y='Year',barmode='stack',height=600,hover_name='Country Name',title=f'Income Share Quintiles - {country}',orientation='h')fig.layout.legend.title = Nonefig.layout.legend.orientation = 'h'fig.layout.legend.x = 0.2fig.layout.xaxis.title = 'Percent of Total Income'return fig
-
Lines 1–15: At the top of the module, we first make the DataFrame definitions as well as column changes, like we did before. Make sure that the code is placed after creating the
poverty
DataFrame because the code depends on the DataFrame. -
Lines 17–20: For the layout part, we add an
h2
element as a title for the new section, aDropdown
component for countries, and aGraph
component right under the last charts we created for the Gini index section. -
Lines 22–39: We construct the
callback
using the code we just worked with.
Adding this code in the right places should add the new functionality to our app. We now have multiple indicators that our users can interact with, and several of them provide different ways of looking at the data.
The four ways to display bar charts can be interesting, but in our case, if we want to allow users to compare more than one country, it would quickly become almost impossible to read. Going back to our Gini index country chart, for example, each selected country typically displays 20 ...