Reusable Dash components

Building Dashboards with Dash and Plotly

Alex Scriven

Data Scientist

DRY Code

 

  • DRY = Don't Repeat Yourself (or refactoring)
    • Remove repeated code
  • Writing functions for repeated tasks
Building Dashboards with Dash and Plotly

DRY Code example

$$

sales_country = ecom_sales\
   .groupby('Country')['OrderValue']\
   .sum()\
   .reset_index(name='Total Sales ($)')\
   .sort_values('Total Sales ($)', 
                ascending=False)

sales_ma_cat = ecom_sales\ .groupby('Major Category')['OrderValue']\ .sum()\ .reset_index(name='Total Sales ($)')\ .sort_values('Total Sales ($)', ascending=False)

Refactored:

def sales_by(col):
    df = ecom_sales\
    .groupby(col)['OrderValue']\
    .sum()\
    .reset_index(name='Total Sales ($)')\
    .sort_values('Total Sales ($)', 
                 ascending=False)
    return df

# Call many times sales_country = sales_by('Country') sales_ma_cat = sales_by('Major Category') sales_mi_cat = sales_by('Minor Category')
Building Dashboards with Dash and Plotly

DRY in Dash

 

  • In Dash: use functions to refactor code
  • Use cases (using functions):
    • Re-using HTML (or any) component
    • Adding consistent styling (CSS can be fiddly!)
    • Updating styles
Building Dashboards with Dash and Plotly

Re-using components

Example: Heavily styled logo

def create_logo():
  logo=html.Img(src=logo_link, style=
  {'margin':'30px 0px 0px 0px',
  'padding':'50px 50px',
  'border':'3px dotted lightblue',
  'background-color':'rgb(230,131,247)'
  })
  return logo

 

app.layout = [
  create_logo(),
  html.Div(),
  # More components
  create_logo(),
  dcc.Graph(id='my_graph'),
  create_logo()
]

The logo is inserted 3 times!

Building Dashboards with Dash and Plotly

Generating a component list

Before:

app.layout = [
  html.Img(src=logo_link),
  html.Br(),
  html.Br(),
  html.H1("Sales breakdowns"),
  html.Br(),
  html.Br(),
  html.Br(),
  ...

After:

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

app.layout = [ html.Img(src=logo_link), *make_break(2), html.H1("Sales breakdowns"), *make_break(3), ...
Building Dashboards with Dash and Plotly

Reusing styling

 

  • Have some shared styling
  • Python dictionary .update() used (warning: unique keys!)
d1 = {'Country':'Australia'}
d2 = {'City':'Sydney'}
d1.update(d2)
print(d1)
{'Country':'Australia', 'City':'Sydney'}
Building Dashboards with Dash and Plotly

Styling functions in Dash

 

Set up the function:

def style_c():
  corp_style={
    'margin':'0 auto',
    'border':'2px solid black',
    'display':'inline-block',
  }
  return corp_style

 

Call in Dash layout:

app.layout = [
 html.Img(src=logo_link, 
 style=style_c()),

dcc.DatePickerSingle( style={'width':'200px'}.update(style_c()) )]
Building Dashboards with Dash and Plotly

Let's practice!

Building Dashboards with Dash and Plotly

Preparing Video For Download...