按国家筛选的销售下拉菜单
当您在工位上埋头工作时,这家电商公司的全球销售经理带来了一个新需求。她很喜欢您最近制作的销售图表,但希望能按国家筛选,并实时查看品类数据的变化。
她特别强调要使用批准的国家名称:United Kingdom、Germany、France、Australia 和 Hong Kong。
🛑 注意: 您可能需要进入 全屏 模式,才能正确查看仪表板,让所有元素并排显示。
本练习是课程的一部分
使用 Dash 和 Plotly 构建仪表板
练习说明
- 在第
16行下方添加名为dcc.Dropdown、标识符为country_dd的下拉组件,以便在回调中使用。 - 在第
30行下方设置回调的输入和输出,将下拉菜单country_dd与图表major_cat连接起来。
交互式实操练习
通过完成这段示例代码来试试这个练习。
from dash import Dash, dcc, html, Input, Output, callback
import plotly.express as px
import pandas as pd
ecom_sales = pd.read_csv('/usr/local/share/datasets/ecom_sales.csv')
logo_link = 'https://assets.datacamp.com/production/repositories/5893/datasets/fdbe0accd2581a0c505dab4b29ebb66cf72a1803/e-comlogo.png'
app = Dash()
app.layout = [
html.Img(src=logo_link, style={'margin': '30px 0px 0px 0px'}),
html.H1('Sales breakdowns'),
html.Div([
html.H2('Controls'),
html.Br(),
html.H3('Country Select'),
# Add a dropdown with identifier
dcc.____(
____='country_dd',
options=['United Kingdom', 'Germany', 'France', 'Australia', 'Hong Kong'],
style={'width': '200px', 'margin': '0 auto'})],
style={'width': '350px', 'height': '350px', 'display': 'inline-block', 'vertical-align': 'top', 'border': '1px solid black', 'padding': '20px'}),
html.Div([
dcc.Graph(id='major_cat'),
html.H2('Major Category', style={'border': '2px solid black', 'width': '200px', 'margin': '0 auto'})],
style={'width': '700px', 'display': 'inline-block'})
]
@callback(
# Set the input and output of the callback to link the dropdown to the graph
____(component_id='____', component_property='____'),
____(component_id='____', component_property='____')
)
def update_plot(input_country):
country_filter = 'All Countries'
sales = ecom_sales.copy(deep=True)
if input_country:
country_filter = input_country
sales = sales[sales['Country'] == country_filter]
ecom_bar_major_cat = sales.groupby('Major Category')['OrderValue'].agg('sum').reset_index(name='Total Sales ($)')
bar_fig_major_cat = px.bar(
title=f'Sales in {country_filter}', data_frame=ecom_bar_major_cat, x='Total Sales ($)', y='Major Category', color='Major Category',
color_discrete_map={'Clothes':'blue','Kitchen':'red','Garden':'green','Household':'yellow'})
return bar_fig_major_cat
if __name__ == '__main__':
app.run(debug=True)