銷售資料的日期選擇器
你打造的互動式銷售儀表板大受好評;不過,業務團隊需要能夠監控每日銷售,以分析模式與趨勢。現在他們希望你能擴充作品,加入一個篩選器,讓使用者在特定日期依主要類別檢視銷售額。
這正是日期選擇器大顯身手的時候!
本練習屬於課程
使用 Dash 與 Plotly 建立儀表板
練習說明
- 在第
18行下方建立一個識別碼為sale_date、名為dcc.DatePickerSingle的日期選擇元件。 - 在第
23行下方將date參數設定為 2011 年 4 月 11 日,讓它成為初始可見日期。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
from dash import Dash, dcc, html, Input, Output, callback
import plotly.express as px
import pandas as pd
from datetime import datetime, date
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'
ecom_sales['InvoiceDate'] = pd.to_datetime(ecom_sales['InvoiceDate'])
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('Sale Date Select'),
# Create a date picker with identifier
____(
id='____',
min_date_allowed=ecom_sales['InvoiceDate'].min(),
max_date_allowed=ecom_sales['InvoiceDate'].max(),
# Set the initial visible date
date=date(____),
initial_visible_month=date(2011, 4, 11),
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='sales_cat'),
html.H2('Daily 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='sale_date', component_property='date')
)
def update_plot(input_date):
sales = ecom_sales.copy(deep=True)
if input_date:
sales = sales[sales['InvoiceDate'] == input_date]
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 on: {input_date}', data_frame=ecom_bar_major_cat, orientation='h',
x='Total Sales ($)', y='Major Category')
return bar_fig_major_cat
if __name__ == '__main__':
app.run(debug=True)