แก้ไข Dashboard ที่เสียหาย
โอ้! ระหว่างการย้าย interactive sales dashboard ขึ้น production ไฟล์เกิดความเสียหาย ไฟล์ส่วนใหญ่ได้รับการกู้คืนแล้ว แต่บางฟังก์ชันและองค์ประกอบสำคัญยังขาดหายไป โดยเฉพาะในส่วนของ callback function ที่ถูกเรียกใช้
ลองใช้ความรู้เรื่อง Dash callbacks เพื่อแก้ไข dashboard นี้กัน
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การสร้างแดชบอร์ดด้วย Dash และ Plotly
คำแนะนำการฝึกหัด
- กำหนดให้ตัวแปร
country_filterมีค่าเป็น'All Countries'ใต้บรรทัดที่34เพื่อให้แสดงผลตอนโหลดหน้า - ป้องกันไม่ให้ DataFrame
ecom_salesถูกเขียนทับภายในฟังก์ชันupdate_plotใต้บรรทัดที่36โดยใช้เมธอด copy - Return figure
bar_fig_major_catจากฟังก์ชันupdate_plotใต้บรรทัดที่45เพื่อให้ Plotly figure แสดงผลใหม่
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
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'),
dcc.Dropdown(
id='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(
Output(component_id='major_cat', component_property='figure'),
Input(component_id='country_dd', component_property='value')
)
def update_plot(input_country):
# Set a default value
country_filter = '____'
# Ensure the DataFrame is not overwritten
sales = ____.____(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 the figure
____
if __name__ == '__main__':
app.run(debug=True)