开始使用免费开始使用

日期选择器回调

糟糕!又出现问题了。您创建的日期选择器仪表板被破坏了,回调代码也无法阅读。

您还记得如何把日期选择器组件与回调结合起来,让仪表板重新正常运行吗?

本练习是课程的一部分

使用 Dash 和 Plotly 构建仪表板

查看课程

练习说明

  • 创建一个回调,并在第 31 行下方将 sale_date 组件与 sales_cat 图表关联。
  • 在第 38 行下方,基于条件使用 input_date 参数来筛选 sales DataFrame 的 InvoiceDate 列。
  • 在第 45 行下方返回 bar_fig_major_cat 图形,以在 Dash 应用中渲染。

交互式实操练习

通过完成这段示例代码来试试这个练习。

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'
ecom_sales['InvoiceDate'] = pd.to_datetime(ecom_sales['InvoiceDate'])

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('Sale Date Select'),
        dcc.DatePickerSingle(
            id='sale_date',
            min_date_allowed=ecom_sales['InvoiceDate'].min(),
            max_date_allowed=ecom_sales['InvoiceDate'].max(),
            date=date(2011, 4, 11),
            initial_visible_month=date(2011, 4, 11),
            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='sales_cat'),
        html.H2('Daily Sales by Major Category', style={'border': '2px solid black', 'width': '400px', 'margin': '0 auto'})], 
    	style={'width': '700px', 'display': 'inline-block'})
]
# Create a callback and link
@callback(
    ____(component_id='____', component_property='____'),
    ____(component_id='____', component_property='____')
)
def update_plot(input_date):
    sales = ecom_sales.copy(deep=True)
    # Conditionally filter the DataFrame using the input
    if ____:
        sales = sales[sales['InvoiceDate'] == input_date]
    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 on: {input_date}', data_frame=ecom_bar_major_cat, orientation='h',
        x='Total Sales ($)', y='Major Category')
    # Return the figure to render
    return ____

if __name__ == '__main__':
    app.run(debug=True)
编辑并运行代码