티스토리 뷰

반응형

dash.plotly 튜토리얼을 따라 첫 번째 dash 앱을 만들어보자!

 

Part 2. Layout | Dash for Python Documentation | Plotly

This tutorial will walk you through a fundamental aspect of Dash apps, the app layout, through 6 self-contained apps. For production Dash apps, we recommend styling the app layout with Dash Enterprise Design Kit. Dash apps are composed of two parts. The fi

dash.plotly.com

예제 앱을 위한 디렉토리(폴더)를 생성하자. (ex. my-first-dash-app)

해당 디렉토리로 이동해서 app.py 파일을 생성한다. 예제 앱에서 이루어지는 모든 코딩은 app.py에 한다.

앱을 실행시키려면 터미널에서 아래 명령어를 수행한다.

$ python app.py

http://127.0.0.1:8050/ 에서 실행시킨 앱을 확인할 수 있고 어플리케이션 실행을 종료하려면 터미널에서 CTRL+C를 누르면 된다.

 


Dash app의 Layout이란?

Dash app의 layout(이하 레이아웃)은 어플리케이션이 어떻게 보일지를 표현하는 것이다. 레이아웃은 컴포넌트의 계층적 트리이다. dash_html_components library는 모든 html태그와 태그의 속성(ex. style, id 등)에 대한 class를 제공한다. dash_core_components library는 고레벨 컴포넌트(ex. 컨트롤, 그래프 등)을 생성한다.

아래 참고:

 


첫 번째 앱 실행하기

아래 코드를 app.py에 복사+붙여넣기하고 $ python run app.py 커맨드를 통해 앱을 실행해보자.

# -*- coding: utf-8 -*-

# Run this app with `python app.py` and
# visit http://127.0.0.1:8050/ in your web browser.

import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
import pandas as pd

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

# assume you have a "long-form" data frame
# see https://plotly.com/python/px-arguments/ for more options
df = pd.DataFrame({
    "Fruit": ["Apples", "Oranges", "Bananas", "Apples", "Oranges", "Bananas"],
    "Amount": [4, 1, 2, 2, 4, 5],
    "City": ["SF", "SF", "SF", "Montreal", "Montreal", "Montreal"]
})

fig = px.bar(df, x="Fruit", y="Amount", color="City", barmode="group")

app.layout = html.Div(children=[
    html.H1(children='Hello Dash'),

    html.Div(children='''
        Dash: A web application framework for Python.
    '''),

    dcc.Graph(
        id='example-graph',
        figure=fig
    )
])

if __name__ == '__main__':
    app.run_server(debug=True)

html태그안에 children속성은 "children=" 이라고 명시해주지 않아도 괄호 안에 적으면 children속성으로 처리된다. 

children 키워드를 생략할 경우에는 반드시 첫번째 인자로 적어야한다.

즉, html.H1(children='Hello Dash')를 html.H1('Hello Dash')로 적을 수 있다. children에는 문자열, 숫자, 단일 컴포넌트 혹은 여러 컴포넌트가 올 수 있다. 

 


dash는 hot-reload를 지원한다!

코드에 변경이 있을 때 실행을 중지시키고 다시 실행해야하는 수고없이 알아서 리로드를 해준다.


dash_html_components에 스타일 적용하기

  • html 태그 스타일의 key는 camelCase로 해야한다.
  • 스타일 속성은 dictionary형태로 적용한다
    • 예) style={ 'textAlign': 'center', 'color': '#888' }
  • html의 class는 dash에서는 className으로 사용한다.

 


재사용 가능한 컴포넌트는 파이썬의 함수로

판다스의 데이터프레임을 인자로 받아 테이블을 생성하는 아래 코드의 예제를 보자.

데이터프레임이 바뀌어도 손쉽게 테이블을 생성할 수 있다.

# Run this app with `python app.py` and
# visit http://127.0.0.1:8050/ in your web browser.

import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd

df = pd.read_csv('https://gist.githubusercontent.com/chriddyp/c78bf172206ce24f77d6363a2d754b59/raw/c353e8ef842413cae56ae3920b8fd78468aa4cb2/usa-agricultural-exports-2011.csv')


def generate_table(dataframe, max_rows=10):
    return html.Table([
        html.Thead(
            html.Tr([html.Th(col) for col in dataframe.columns])
        ),
        html.Tbody([
            html.Tr([
                html.Td(dataframe.iloc[i][col]) for col in dataframe.columns
            ]) for i in range(min(len(dataframe), max_rows))
        ])
    ])


external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

app.layout = html.Div(children=[
    html.H4(children='US Agriculture Exports (2011)'),
    generate_table(df)
])

if __name__ == '__main__':
    app.run_server(debug=True)
반응형
댓글
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함