Dash의 콜백

Dash와 Plotly로 대시보드 만들기

Alex Scriven

Data Scientist

콜백이란?

 

  • 상호작용으로 기능 실행
    • 사용자가 요소와 상호작용
      • -> Python 함수가 실행됨
        • --> 무언가가 변경됨

$$

$$

$$

  • 이유: 대화형성 향상 ✨
Dash와 Plotly로 대시보드 만들기

Dash의 콜백

  • 데코레이터로 시작
    • from dash import Input, Output 사용
  • Output: 함수 반환을 보낼 위치
    • component_id: 대상 컴포넌트
    • component_property: 변경될 속성
  • Input: 콜백을 트리거하는 것
    • component_property: 함수에서 사용할 속성

 

@callback(

Output(component_id='my_plot', component_property='figure'),
Input(component_id='my_input', component_property='value')
)
def some_function(data): # Subset Data # Recreate Figure return fig
Dash와 Plotly로 대시보드 만들기

Dash의 드롭다운

 

dcc.Dropdown(id='title_dd',
             options=['Title 1', 'Title 2'])
  • 값 목록
Dash와 Plotly로 대시보드 만들기

드롭다운 콜백

app.layout =[

dcc.Dropdown(id='title_dd', options=['Title 1', 'Title 2']),
dcc.Graph(id='my_graph')])
@callback( Output(component_id='my_graph', component_property='figure'),
Input(component_id='title_dd', component_property='value') )
# @callback()
def update_plot(selection):
    title = "None Selected"
    if selection:
        title = selection

bar_fig = px.bar( data_frame=ecom_sales, title=f'{title}', x='Total Sales ($)', y='Country')
return bar_fig
Dash와 Plotly로 대시보드 만들기

첫 드롭다운

크롬 브라우저에서 총 매출(x축)과 국가(y축) 막대 차트 위에 드롭다운이 있고 옵션은 Title 1, Title 2입니다. 마우스가 각 옵션을 선택하면 그래프 제목이 해당 값으로 바뀝니다

Dash와 Plotly로 대시보드 만들기

필터로서의 드롭다운

  • 일반적인 사용: 드롭다운으로 플롯 DataFrame 필터링
# @callback()
def update_plot(input_country):
    country = 'All Countries'

sales = ecom_sales.copy(deep=True)
if input_country: country = input_country sales = sales[sales['Country'] == country]
bar_fig = px.bar( data_frame=sales, title=f"Sales in {country}", x='Total Sales ($)', y='Country') return bar_fig
Dash와 Plotly로 대시보드 만들기

작동하는 필터

 

크롬 브라우저에서 총 매출(x축)과 국가(y축) 막대 차트 위에 국가명을 옵션으로 한 드롭다운이 있습니다. 마우스가 각 국가를 선택하면 제목이 바뀌고 차트가 단일 막대로 필터링됩니다

Dash와 Plotly로 대시보드 만들기

연습해 봅시다!

Dash와 Plotly로 대시보드 만들기

Preparing Video For Download...