Hergebruikbare Dash-componenten

Dashboards bouwen met Dash en Plotly

Alex Scriven

Data Scientist

DRY-code

 

  • DRY = Don't Repeat Yourself (of refactoren)
    • Herhaalcode verwijderen
  • Functies schrijven voor terugkerende taken
Dashboards bouwen met Dash en Plotly

Voorbeeld DRY-code

$$

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)

Gerefactord:

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

# Meerdere keren aanroepen sales_country = sales_by('Country') sales_ma_cat = sales_by('Major Category') sales_mi_cat = sales_by('Minor Category')
Dashboards bouwen met Dash en Plotly

DRY in Dash

 

  • In Dash: gebruik functies om code te refactoren
  • Use-cases (met functies):
    • HTML- (of andere) component hergebruiken
    • Consistente styling toevoegen (CSS kan lastig zijn!)
    • Styles updaten
Dashboards bouwen met Dash en Plotly

Componenten hergebruiken

Voorbeeld: zwaar gestyled 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(),
  # Meer componenten
  create_logo(),
  dcc.Graph(id='my_graph'),
  create_logo()
]

Het logo wordt 3× ingevoegd!

Dashboards bouwen met Dash en Plotly

Een componentlijst genereren

Voor:

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

Na:

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), ...
Dashboards bouwen met Dash en Plotly

Styling hergebruiken

 

  • Gedeelde styling
  • Python-dict .update() gebruikt (let op: unieke keys!)
d1 = {'Country':'Australia'}
d2 = {'City':'Sydney'}
d1.update(d2)
print(d1)
{'Country':'Australia', 'City':'Sydney'}
Dashboards bouwen met Dash en Plotly

Stylingfuncties in Dash

 

Stel de functie op:

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

 

Aanroepen in Dash-layout:

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

dcc.DatePickerSingle( style={'width':'200px'}.update(style_c()) )]
Dashboards bouwen met Dash en Plotly

Laten we oefenen!

Dashboards bouwen met Dash en Plotly

Preparing Video For Download...