재사용 가능한 Dash 컴포넌트

Dash와 Plotly로 대시보드 만들기

Alex Scriven

Data Scientist

DRY 코드

 

  • DRY = Don't Repeat Yourself(또는 리팩터링)
    • 중복 코드 제거
  • 반복 작업을 위한 함수 작성
Dash와 Plotly로 대시보드 만들기

DRY 코드 예시

$$

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)

리팩터링:

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

# 여러 번 호출 sales_country = sales_by('Country') sales_ma_cat = sales_by('Major Category') sales_mi_cat = sales_by('Minor Category')
Dash와 Plotly로 대시보드 만들기

Dash에서의 DRY

 

  • Dash에서: 함수를 사용해 코드 리팩터링
  • 사용 사례(함수 활용):
    • HTML(또는 기타) 컴포넌트 재사용
    • 일관된 스타일 적용(CSS는 까다로울 수 있음)
    • 스타일 업데이트
Dash와 Plotly로 대시보드 만들기

컴포넌트 재사용

예: 스타일이 많은 로고

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

로고가 3번 삽입됩니다!

Dash와 Plotly로 대시보드 만들기

컴포넌트 리스트 생성

이전:

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

이후:

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와 Plotly로 대시보드 만들기

스타일 재사용

 

  • 공통 스타일 일부 사용
  • Python 딕셔너리 .update() 사용 (주의: 키는 고유해야 함)
d1 = {'Country':'Australia'}
d2 = {'City':'Sydney'}
d1.update(d2)
print(d1)
{'Country':'Australia', 'City':'Sydney'}
Dash와 Plotly로 대시보드 만들기

Dash에서 스타일 함수

 

함수 설정:

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

 

Dash 레이아웃에서 호출:

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

dcc.DatePickerSingle( style={'width':'200px'}.update(style_c()) )]
Dash와 Plotly로 대시보드 만들기

Lass uns üben!

Dash와 Plotly로 대시보드 만들기

Preparing Video For Download...