銷售資料的滑桿
你用日期選擇器強化了對這家全球電商公司資料的趨勢與模式分析。現在他們進一步想知道,是哪些類別在帶動「高單價」訂單。
公司希望你建立一個工具,讓他們可以選擇一個數值(任何數值都行!),接著圖表會顯示訂單金額大於該數值的銷售筆數,並依主要類別分拆呈現。
你知道用一個範圍輸入會很適合這個需求。
本練習屬於課程
使用 Dash 與 Plotly 建立儀表板
練習說明
- 在第
16行下方加入一個名為dcc.Slider、識別碼為value_slider的滑桿元件,用來選擇最低訂單金額。 - 在第
20行下方將滑桿的value參數設為0。 - 在第
22行下方將滑桿的step參數設為50。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
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('Minimum OrderValue Select'),
# Add a slider input
____(id='value_slider',
min=ecom_sales['OrderValue'].min(),
max=ecom_sales['OrderValue'].max(),
# Set the starting value of the slider
____=____,
# Set the step increment of the slider
____=____,
vertical=False)],
style={'width':'350px', 'height':'350px', 'display':'inline-block', 'vertical-align':'top', 'border':'1px solid black', 'padding':'20px'}),
html.Div([
dcc.Graph(id='sales_cat'),
html.H2('Sales by Major Category', style={ 'border':'2px solid black', 'width':'400px', 'margin':'0 auto'})],
style={'width':'700px','display':'inline-block'})
]
@callback(
Output(component_id='sales_cat', component_property='figure'),
Input(component_id='value_slider', component_property='value')
)
def update_plot(min_val):
sales = ecom_sales.copy(deep=True)
if min_val:
sales = sales[sales['OrderValue'] >= min_val]
ecom_bar_major_cat = sales.groupby('Major Category')['OrderValue'].size().reset_index(name='Total Sales Volume')
bar_fig_major_cat = px.bar(
title=f'Sales with order value: {min_val}',data_frame=ecom_bar_major_cat, orientation='h',
x='Total Sales Volume', y='Major Category')
return bar_fig_major_cat
if __name__ == '__main__':
app.run(debug=True)