Dash

Neoplanetz·2022년 3월 14일
0

Dash

목록 보기
1/1
post-thumbnail

Dash Layout 설명

💡 Use this template to create guidelines for all of the engineers on your team. Add a table of contents by typing `/table of` and pressing `enter`.

Dash Apps


Dash Layout

  • 기본적인 Dash의 외형을 표현하고, Python 코드로 되어있어 Python 코드 실행시키듯이 실행하면 됨
python app.py
  • 다음과 같이 app.py를 생성한다
# Run this app with `python app.py` and
# visit http://127.0.0.1:8050/ in your web browser.

from dash import Dash, html, dcc
import plotly.express as px
import pandas as pd

app = Dash(__name__)

# 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 your data.
    '''),

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

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

  • app.py를 실행시킨 후 웹브라우져를 통해 http://127.0.0.1:8050/ 로 이동하면 실행결과 확인할 수 있음
  • app.layout 은 2개의 컴포넌트로 구성되어있음
    • html.Div
    • dcc.Graph
  • Dash HTML 컴포넌트 모듈(dash.html)은 모든 HTML Tag를 가지고 있음
    • html.H1(children=’Hello Dash’) 컴포넌트는

      Hello Dash

      HTML 문법과 같음
  • Dash Core Components 모듈(dash.dcc)은 고차원 컴포넌트고 React.js 라이브러리를 통해 JavaScript, HTML, CSS와 함께 생성되어진다
  • children 속성은 항상 첫번째 속성이고, 생략 가능하다(html.H1(children=’Hello Das’) 와 html.H1(’Hello Dash’)는 같다)
  • Dash 는 기본적으로 hot-reloading 기능을 지원한다. 코드부분에 app.run_server(debug=True)로 되어있으면 코드 수정한 부분이 있을시 자동으로 핫리로딩 하여 서버에 적용해준다

Dash HTML Components

  • Dash HTML Components(dash.html)는 모든 HTML 태그 및 HTML arguments들을 포함한다
# Run this app with `python app.py` and
# visit http://127.0.0.1:8050/ in your web browser.

from dash import Dash, dcc, html
import plotly.express as px
import pandas as pd

app = Dash(__name__)

colors = {
    'background': '#111111',
    'text': '#7FDBFF'
}

# 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")

fig.update_layout(
    plot_bgcolor=colors['background'],
    paper_bgcolor=colors['background'],
    font_color=colors['text']
)

app.layout = html.Div(style={'backgroundColor': colors['background']}, children=[
    html.H1(
        children='Hello Dash',
        style={
            'textAlign': 'center',
            'color': colors['text']
        }
    ),

    html.Div(children='Dash: A web application framework for your data.', style={
        'textAlign': 'center',
        'color': colors['text']
    }),

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

if __name__ == '__main__':
    app.run_server(debug=True)
  • 위의 예제는 html.Div html.H1 Components에 style 속성으로 수정했다
html.H1('Hello Dash', style={'textAlign': 'center', 'color': '#7FDBFF'})
  • 위의 코드는

    Hello Dash

    와 같다
  • dash.html 과 HTML 속성 간에는 다음과 같으 차이점이 존재한다
    • HTML의 style 속성은 구분자로 세미콜론을 사용하고 Dash에서는 dictionary 방식으로 표현
    • style dictionary의 속성값은 camelCased 방식으로 표현(text-align은 textAlign으로 표현)
    • HTML의 class 특성은 Dash에서는 className 으로 표현

Reusable Components

  • Table과 같은 복잡한 재사용가능한 component를 언어와 컨텍스트 변환 없이 사용 가능
# Run this app with `python app.py` and
# visit http://127.0.0.1:8050/ in your web browser.

from dash import Dash, 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))
        ])
    ])

app = Dash(__name__)

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

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

Dash Core Components Module

  • Dash Core Components module(dash.dcc)는 Graph라는 component를 가지고 있음
  • Graph는 plotly.js JavaScript 기반을 사용하는 Interactive data visualization를 보여줌
  • Graph의 figure 특성은 plotly.py에서 사용되는 figure 와 동일하다. Plotly는 35종류의 차트를 미려하게 보여주는 라이브러리다
  • 다음 예제는 pandas dataframe으로 부터 scatter plot을 보여준다
# Run this app with `python app.py` and
# visit http://127.0.0.1:8050/ in your web browser.

from dash import Dash, dcc, html
import plotly.express as px
import pandas as pd

app = Dash(__name__)

df = pd.read_csv('https://gist.githubusercontent.com/chriddyp/5d1ea79569ed194d432e56108a04d188/raw/a9f9e8076b837d541398e999dcbac2b2826a81f8/gdp-life-exp-2007.csv')

fig = px.scatter(df, x="gdp per capita", y="life expectancy",
                 size="population", color="continent", hover_name="country",
                 log_x=True, size_max=60)

app.layout = html.Div([
    dcc.Graph(
        id='life-exp-vs-gdp',
        figure=fig
    )
])

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

Markdown

  • Dash에서는 Dash Core Components(dash.dcc)를 통해 Markdown 문서를 작성할 수 있다
# Run this app with `python app.py` and
# visit http://127.0.0.1:8050/ in your web browser.

from dash import Dash, html, dcc

app = Dash(__name__)

markdown_text = '''
### Dash and Markdown

Dash apps can be written in Markdown.
Dash uses the [CommonMark](http://commonmark.org/)
specification of Markdown.
Check out their [60 Second Markdown Tutorial](http://commonmark.org/help/)
if this is your first introduction to Markdown!
'''

app.layout = html.Div([
    dcc.Markdown(children=markdown_text)
])

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

Core Components

  • Dash Core Components(dash.dcc)는 dropdowns, graphs, markdown blocks 등과 같이 높은 레벨의 components들을 가지고 있다
  • 모든 Dash Core Components 들을 보고 싶으면 다음의 링크를 참고(https://dash.plotly.com/dash-core-components)
# Run this app with `python app.py` and
# visit http://127.0.0.1:8050/ in your web browser.

from dash import Dash, html, dcc

app = Dash(__name__)

app.layout = html.Div([
    html.Div(children=[
        html.Label('Dropdown'),
        dcc.Dropdown(['New York City', 'Montréal', 'San Francisco'], 'Montréal'),

        html.Br(),
        html.Label('Multi-Select Dropdown'),
        dcc.Dropdown(['New York City', 'Montréal', 'San Francisco'],
                     ['Montréal', 'San Francisco'],
                     multi=True),

        html.Br(),
        html.Label('Radio Items'),
        dcc.RadioItems(['New York City', 'Montréal', 'San Francisco'], 'Montréal'),
    ], style={'padding': 10, 'flex': 1}),

    html.Div(children=[
        html.Label('Checkboxes'),
        dcc.Checklist(['New York City', 'Montréal', 'San Francisco'],
                      ['Montréal', 'San Francisco']
        ),

        html.Br(),
        html.Label('Text Input'),
        dcc.Input(value='MTL', type='text'),

        html.Br(),
        html.Label('Slider'),
        dcc.Slider(
            min=0,
            max=9,
            marks={i: f'Label {i}' if i == 1 else str(i) for i in range(1, 6)},
            value=5,
        ),
    ], style={'padding': 10, 'flex': 1})
], style={'display': 'flex', 'flex-direction': 'row'})

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

Summary

  • Dash의 layout은 Dash의 외형을 나타냄
  • layout은 components들의 계층적인 트리로 구성되어있음
  • Dash HTML Components(dash.html)은 모든 HTML 태그와 키워드 특성(style, class, id)을 위한 class 들을 제공함
  • Dash Core Components(dash.dcc)는 controls와 graphs와 같이 높은 수준의 components들을 생성함

Dash Callbacks

profile
Another Future Follower

0개의 댓글