以國家篩選的銷售下拉選單
當你在座位上忙著工作時,這家電商公司的全球銷售經理帶來了一個新挑戰。她很喜歡你最近做的銷售圖表,但希望能依國家篩選,並即時看到各類別資料的更新。
她特別強調必須使用核准的國家名稱:United Kingdom、Germany、France、Australia,以及 Hong Kong。
🛑 Note: 你可能需要切換到 Full screen 模式,才能正確看到儀表板中並排顯示的所有元件。
本練習屬於課程
使用 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)