修复出问题的仪表板
糟糕!在将您的交互式销售仪表板部署到生产环境时,文件损坏了。大部分文件已经恢复;不过,一些关键函数和元素仍有缺失,主要集中在被触发的回调函数一带。
您能用自己对 Dash 回调的了解来修复这个仪表板吗?
本练习是课程的一部分
使用 Dash 和 Plotly 构建仪表板
练习说明
- 在第
34行下面,将变量country_filter设为'All Countries',以便页面加载时显示该值。 - 在第
36行下面的update_plot函数中,使用副本方法,确保不会覆盖ecom_salesDataFrame。 - 在第
45行下面,从update_plot函数返回bar_fig_major_cat图形,这样 Plotly 图形会重新渲染。
交互式实操练习
通过完成这段示例代码来试试这个练习。
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)