Get startedGet started for free

DRY-styling Dash components

Your clever use of Python functions allowed you to save some space in the last exercise. Yet, you think there is more that can be done to refactor this dashboard.

An additional function has been created to render multiple HTML breaks, which you can utilize in the code. Along with this, there seems to be a lot of overlap in the CSS styling you have added to components. This can also be cleaned up, you think!

The common style elements you have noticed are: 'display':'inline-block','margin':'0 auto','padding':'20px'

The make_break() function has been defined for you on line 14, which takes an argument specifying how many HTML break tags to create and returns these in a list.

This exercise is part of the course

Building Dashboards with Dash and Plotly

View Course

Exercise instructions

  • Create a function that will return a style dictionary with all the common style elements ('display':'inline-block','margin':'0 auto','padding':'20px') below line 26.
  • Use the make_break() function (already created for you) to add the number of breaks specified under each comment Insert X HTML breaks below lines 33, 36, and 47.
  • Use the styling function to add styling to the .H2() below line 43.
  • Use the styling function to add to the specific styling already on the DatePickerSingle() below line 55.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

import dash
from dash import dcc, html
import plotly.express as px
import pandas as pd
from dash.dependencies import Input, Output
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.Dash(__name__)

def make_break(num_breaks):
    br_list = [html.Br()] * num_breaks
    return br_list

def add_logo():
    corp_logo = html.Img(
        src=logo_link, 
        style={'margin':'20px 20px 5px 5px',
              'border':'1px dashed lightblue',
              'display':'inline-block'})
    return corp_logo

# Create a function to add corporate styling
def style_c():
    layout_style=____
    return ____

app.layout = html.Div([
  add_logo(),
  # Insert two HTML breaks
  ____,
  html.H1('Sales breakdowns'),
  # Insert three HTML breaks
  ____,
  html.Div(
    children=[
    html.Div(
        children=[
        add_logo(),
        # Style using the styling function
        html.H2('Controls', ____),
        add_logo(),
        html.H3('Sale Date Select'),
        # Insert two HTML breaks
        ____,
        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),
          	# Add styling using the styling function
            style={'width':'200px'}.____(____)),
        ],
        style={'width':'550px', 'height':'350px', 'vertical-align':'top', 'border':'1px solid black',
        'display':'inline-block', 'margin':'0px 40px'}),
    html.Div(children=[
            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'}
             ),
    ]),
    add_logo(),
    ], 
  style={'text-align':'center', 'display':'inline-block', 'width':'100%'}
  )

@app.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_server(debug=True)
Edit and Run Code