Thanh trượt cho dữ liệu doanh số
Phân tích xu hướng và mẫu hình trong dữ liệu của công ty thương mại điện tử toàn cầu đã được cải thiện đáng kể nhờ các bộ chọn ngày. Có thêm một yêu cầu nữa: xem những danh mục nào đang tạo ra các đơn hàng "giá trị lớn".
Công ty đề nghị bạn xây dựng một công cụ cho phép họ chọn một giá trị (bất kỳ giá trị nào!) và một biểu đồ sẽ hiển thị có bao nhiêu giao dịch có giá trị đơn hàng lớn hơn giá trị đó, được tách theo các danh mục chính.
Bạn biết rằng điều này sẽ phù hợp khi dùng một input dạng khoảng (range input).
Bài tập này là một phần của khóa học
Xây dựng Dashboard với Dash và Plotly
Hướng dẫn bài tập
- Thêm một thành phần thanh trượt
dcc.Slidervới định danhvalue_sliderbên dưới dòng16để chọn giá trị đơn hàng tối thiểu. - Đặt tham số
valuecủa thanh trượt thành0bên dưới dòng20. - Đặt tham số
stepcủa thanh trượt thành50bên dưới dòng22.
Bài tập tương tác thực hành trực tiếp
Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.
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)