Yeniden kullanılabilir Dash bileşenleri

Dash ve Plotly ile Paneller Oluşturma

Alex Scriven

Data Scientist

DRY Kod

 

  • DRY = Kendini Tekrarlama (refaktoring)
    • Tekrarlanan kodu kaldır
  • Tekrarlanan işler için fonksiyon yaz
Dash ve Plotly ile Paneller Oluşturma

DRY Kod örneği

$$

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)

Refaktör edilmiş:

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

# Birden çok kez çağır sales_country = sales_by('Country') sales_ma_cat = sales_by('Major Category') sales_mi_cat = sales_by('Minor Category')
Dash ve Plotly ile Paneller Oluşturma

Dash’te DRY

 

  • Dash’te: kodu fonksiyonlarla refaktör edin
  • Kullanım durumları (fonksiyonla):
    • HTML (veya diğer) bileşenleri yeniden kullanma
    • Tutarlı stil ekleme (CSS zahmetli olabilir)
    • Stilleri güncelleme
Dash ve Plotly ile Paneller Oluşturma

Bileşenleri yeniden kullanma

Örnek: Yoğun stilli 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(),
  # Daha fazla bileşen
  create_logo(),
  dcc.Graph(id='my_graph'),
  create_logo()
]

Logo 3 kez eklendi!

Dash ve Plotly ile Paneller Oluşturma

Bileşen listesi üretme

Öncesi:

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

Sonrası:

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), ...
Dash ve Plotly ile Paneller Oluşturma

Stili yeniden kullanma

 

  • Ortak bir stil olsun
  • Python sözlüğü .update() kullanılır (uyarı: anahtarlar benzersiz olmalı!)
d1 = {'Country':'Australia'}
d2 = {'City':'Sydney'}
d1.update(d2)
print(d1)
{'Country':'Australia', 'City':'Sydney'}
Dash ve Plotly ile Paneller Oluşturma

Dash’te stil fonksiyonları

 

Fonksiyonu kurun:

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

 

Dash yerleşiminde çağırın:

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

dcc.DatePickerSingle( style={'width':'200px'}.update(style_c()) )]
Dash ve Plotly ile Paneller Oluşturma

Haydi pratik yapalım!

Dash ve Plotly ile Paneller Oluşturma

Preparing Video For Download...