Aan de slagBegin gratis

Dash-componenten hergebruiken

Je dashboards slaan aan, vooral je recente date picker-app. Een senior manager was enthousiast, maar vroeg om wat aanpassingen: gebruik het corporate gestylede logo en toon het op meerdere plekken.

Om je code netjes te houden, is het tijd om een herbruikbare Python-functie voor het logo te maken.

De goedgekeurde logostijl is: 'width':'75px', 'margin':'20px 20px 5px 5px', 'border':'1px dashed lightblue', 'display':'inline-block'

Deze oefening maakt deel uit van de cursus

Dashboards bouwen met Dash en Plotly

Bekijk cursus

Oefeninstructies

  • Maak onder regel 11 een herbruikbare componentfunctie add_logo() die de component corp_logo retourneert.
  • Maak binnen deze functie onder regel 13 een Dash-afbeeldingselement corp_logo met de juiste HTML-component en de meegegeven stijl.
  • Roep de functie add_logo() aan op elk van de 4 gemarkeerde plekken onder de regels 20, 27, 30 en 46.

Interactieve oefening met praktijkervaring

Probeer deze oefening door deze voorbeeldcode aan te vullen.

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()

# Create a reusable component function called add_logo
____ ____():
    # Create a Dash image element
    corp_logo = ____(
        src=logo_link, 
        style={'width':'75px', 'margin':'20px 20px 5px 5px', 'border':'1px dashed lightblue', 'display':'inline-block'})
    return corp_logo

app.layout = [
  # Insert the logo (1)
  ____,
  html.Br(),
  html.H1('Sales breakdowns'),
  html.Br(),
  html.Br(),
  html.Div([
        # Insert the logo (2)
        ____,
        html.H2('Controls', style={'margin':'0 10px','display':'inline-block'}),
        # Insert the logo (3)
        ____,
        html.H3('Sale Date Select'),
        html.Br(),
        dcc.DatePickerSingle(
            id='sale_date',
            min_date_allowed=ecom_sales.InvoiceDate.min(),
            max_date_allowed=ecom_sales.InvoiceDate.max(),
            initial_visible_month=date(2011, 4, 1),
            date=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'}),
  # Insert the logo (4)
  ____
]
@callback(
    Output(component_id='sales_cat', component_property='figure'),
    Input(component_id='sale_date', component_property='date')
)
def update_plot(input_date):
    sales = ecom_sales.copy(deep=True)
    if input_date:
        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 bar_fig_major_cat

if __name__ == '__main__':
    app.run(debug=True)
Code bewerken en uitvoeren