매출 데이터용 날짜 선택기
여러분이 만든 대화형 매출 대시보드가 큰 호응을 얻었어요. 하지만 영업팀이 패턴과 추세를 분석하려면 일일 매출을 모니터링할 수 있어야 하죠. 특정 날짜에 대분류별 매출을 조회할 수 있도록 필터를 추가해 달라는 요청을 받았습니다.
이럴 때는 날짜 선택기가 제격이에요!
이 연습은 강의의 일부입니다
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)