การอัปเดตชื่อกราฟ
บริษัท e-commerce ที่คุณทำงานด้วยมีความท้าทายใหม่มาให้
บริษัทต้องการให้ผู้ใช้สามารถปรับแต่งกราฟได้ด้วยตัวเอง นั่นคือชื่อกราฟควรตั้งค่าได้ เพื่อให้ผู้ใช้รู้สึกว่าแดชบอร์ดนี้เป็นของตัวเอง
นี่คืองานสำหรับ user-input component!
ช่วยบริษัทพัฒนา Dash app โดยรับข้อความจากผู้ใช้เพื่ออัปเดตชื่อกราฟ
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การสร้างแดชบอร์ดด้วย Dash และ Plotly
คำแนะนำการฝึกหัด
~- เพิ่ม text input component ชื่อ dcc.Input พร้อม identifier add_user_name ใต้บรรทัดที่ 33
- ตั้งค่าพารามิเตอร์
debounceเพื่อให้ callback ถูกเรียกเมื่อผู้ใช้กด 'Enter' ใต้บรรทัดที่36 - ตั้งค่าพารามิเตอร์
requiredเพื่อให้ผู้ใช้ไม่จำเป็นต้องป้อนข้อมูลก็สามารถแสดงกราฟได้ ใต้บรรทัดที่38
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
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'
def make_break(num_breaks):
br_list = [html.Br()] * num_breaks
return br_list
def add_logo():
corp_logo = html.Img(
src=logo_link,
style={'width':'75px','margin':'20px 20px 5px 5px','border':'1px dashed lightblue','display':'inline-block'})
return corp_logo
def style_c():
layout_style={'display':'inline-block','margin':'0 auto','padding':'20px'}
return layout_style
app = Dash()
app.layout = [
add_logo(),
*make_break(2),
html.H1('Sales Dashboard'),
*make_break(3),
html.Div([
html.H2('Controls', style=style_c()),
html.H3('Customize plot title'),
*make_break(2),
# Add a text input
dcc.____(id='add_user_name', type='____',
placeholder='Enter your name',
# Ensure input is triggered with 'Enter'
____=____,
# Ensure the plot can load without a selection
____=____,
style={'width':'200px', 'height':'30px'})],
style={'width':'350px', 'height':'350px', 'vertical-align':'top', 'border':'1px solid black',
'display':'inline-block', 'margin':'0px 80px'}),
html.Div([
dcc.Graph(id='sales_plot'),
html.H2('Sales Quantity by Country', style={ 'border':'2px solid black', 'width':'400px', 'margin':'0 auto'})],
style={'width':'500px','display':'inline-block'})
]
@callback(
Output(component_id='sales_plot', component_property='figure'),
Input(component_id='add_user_name', component_property='value')
)
def update_plot(entered_name):
title_value = 'No Name Entered'
sales = ecom_sales.copy(deep=True)
if entered_name:
title_value = entered_name
fig = px.scatter(data_frame=sales,
y='OrderValue', x='Quantity', color='Country',title=f'Plot generated for: {title_value}')
return fig
if __name__ == '__main__':
app.run(debug=True)