销售数据的滑块
借助您添加的日期选择器,针对这家全球电商公司的数据进行趋势与模式分析已有显著提升。现在还有一项新需求:查看究竟是哪些类别在驱动那些"大额"订单。
公司希望您构建一个工具:他们可以选择一个数值(任意值都可以!),然后图表会显示订单金额大于该数值的销售数量,并按主要类别进行拆分。
您很清楚,这可以通过一个范围输入来很好地实现。
本练习是课程的一部分
使用 Dash 和 Plotly 构建仪表板
练习说明
- 在第
16行下面添加一个名为dcc.Slider、标识符为value_slider的滑块组件,用于选择最小订单金额。 - 在第
20行下面将该滑块的value参数设置为0。 - 在第
22行下面将该滑块的step参数设置为50。
交互式实操练习
通过完成这段示例代码来试试这个练习。
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)