Search⌘ K
AI Features

Incorporating the Functionality into the App

Explore how to incorporate interactive bar charts into your Dash app using drop-down menus. Learn to create faceted charts that display multiple countries separately, improve readability with color coding, dynamic titles, and adjust chart layout for better user experience.

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.

C++
import re
income_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_df
dcc.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 PreventUpdate
fig = 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 = None
fig.layout.legend.orientation = 'h'
fig.layout.legend.x = 0.2
fig.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, a Dropdown component for countries, and a Graph component right under the last charts we created for the Gini index section.

  • Lines 22–39: We construct the callback using the ...