2 minute read

camp2의 temp

1. Dash

Dash란?

HTML 기초

2. Dash 사용하기

###


dropdown

import dash
from dash import dcc, html

app = dash.Dash(__name__)

app.layout = html.Div(
    [
        html.Div(
            [
                html.Label('Dropdown'),
                dcc.Dropdown(
                    options=[
                        {'label': 'New York City', 'value': 'NYC'},
                        {'label': u'Montréal', 'value': 'MTL'},
                        {'label': 'San Francisco', 'value': 'SF'},
                    ],
                    value='MTL',
                ),
                html.Br(),
                html.Label('Multi-Select Dropdown'),
                dcc.Dropdown(
                    options=[
                        {'label': 'New York City', 'value': 'NYC'},
                        {'label': u'Montréal', 'value': 'MTL'},
                        {'label': 'San Francisco', 'value': 'SF'},
                    ],
                    value=['MTL', 'SF'],
                    multi=True,
                ),
            ],
            style={'padding': 10, 'flex': 1},
        ),
    ],
    style={'display': 'flex', 'flex-direction': 'row'},
)

if __name__ == '__main__':
    app.run_server(debug=True)
  • option은 딕셔너리 형태, label과 value가 필요
  • 기본값 지정 가능
import dash
from dash import dcc, html

app = dash.Dash(__name__)

app.layout = html.Div(
    [
        html.Div(
            children=[
                html.Label('Checkboxes'),
                dcc.Checklist(
                    options=[
                        {'label': 'New York City', 'value': 'NYC'},
                        {'label': u'Montréal', 'value': 'MTL'},
                        {'label': 'San Francisco', 'value': 'SF'},
                    ],
                    value=['MTL', 'SF'],
                ),
                html.Br(),
                html.Label('Text Input'),
                dcc.Input(value='MTL', type='text'),    # 타입을 텍스트로 줘야 text 입력 가능, MTL은 지워도 가능 지우면 입력창이 비어있게 됨, placeholder사용 가능
                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)

콜백

콜백함수 예시

import time

def waiter(cus):
    time.sleep(3)
    print("Hi")
    cus()

def customer1():
    print("Americano")

def customer2():
    print("Espresso")

waiter(customer2)

실행 결과 Hi Espresso 가 출력됨

from dash import Dash, dcc, html, Input, Output
import plotly.express as px

import pandas as pd

app = Dash(__name__)

df = pd.read_csv('https://plotly.github.io/datasets/country_indicators.csv')    #데이터셋 불러오기

app.layout = html.Div(
    [
        html.Div(
            [
                html.Div(
                    [
                        dcc.Dropdown(
                            df['Indicator Name'].unique(),  # options
                            'Fertility rate, total (births per woman)', # value
                            id='xaxis-column',
                        ),
                        dcc.RadioItems(
                            ['Linear', 'Log'],
                            'Linear',
                            id='xaxis-type',
                            inline=True,
                        ),
                    ],
                    # 각 div마다 스타일 지정
                    style={'width': '48%', 'display': 'inline-block'},
                ),
                html.Div(
                    [
                        dcc.Dropdown(
                            df['Indicator Name'].unique(),
                            'Life expectancy at birth, total (years)',
                            id='yaxis-column',
                        ),
                        dcc.RadioItems(
                            ['Linear', 'Log'],
                            'Linear',
                            id='yaxis-type',
                            inline=True,
                        ),
                    ],
                    style={
                        'width': '48%',
                        'float': 'right',
                        'display': 'inline-block',
                    },
                ),
            ]
        ),
        dcc.Graph(id='indicator-graphic'),  # 콜백 함수가 있으면 채워지게 될 것이라는 추측을 할 수 있음
        dcc.Slider(
            df['Year'].min(),
            df['Year'].max(),
            step=None,
            id='year--slider',
            value=df['Year'].max(),
            marks={str(year): str(year) for year in df['Year'].unique()},
        ),
    ]
)

# output 1개, input 5개
@app.callback(
    Output('indicator-graphic', 'figure'),
    Input('xaxis-column', 'value'),
    Input('yaxis-column', 'value'),
    Input('xaxis-type', 'value'),
    Input('yaxis-type', 'value'),
    Input('year--slider', 'value'),
)

# input이 5개였으므로 파라미터 5개
def update_graph(
    xaxis_column_name, yaxis_column_name, xaxis_type, yaxis_type, year_value
):
    dff = df[df['Year'] == year_value]      # 연도로 필터링(슬라이더의 value)

    fig = px.scatter(
        x=dff[dff['Indicator Name'] == xaxis_column_name]['Value'],     # 한번 더 필터링
        y=dff[dff['Indicator Name'] == yaxis_column_name]['Value'],
        hover_name=dff[dff['Indicator Name'] == yaxis_column_name][
            'Country Name'
        ],
    )

    fig.update_layout(
        margin={'l': 40, 'b': 40, 't': 10, 'r': 0}, hovermode='closest'
    )

    # xaxes을 바꿈
    fig.update_xaxes(
        title=xaxis_column_name,
        type='linear' if xaxis_type == 'Linear' else 'log',
    )

    fig.update_yaxes(
        title=yaxis_column_name,
        type='linear' if yaxis_type == 'Linear' else 'log',
    )

    return fig


if __name__ == '__main__':
    app.run_server(debug=True)
# -*- coding: utf-8 -*-
from dash import Dash, dcc, html, Input, Output

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

app = Dash(__name__, external_stylesheets=external_stylesheets)

all_options = {
    'America': ['New York City', 'San Francisco', 'Cincinnati'],
    'Canada': [u'Montréal', 'Toronto', 'Ottawa'],
}
app.layout = html.Div(
    [
        dcc.RadioItems(
            list(all_options.keys()),
            'America',
            id='countries-radio',
        ),
        html.Hr(),
        dcc.RadioItems(id='cities-radio'),
        html.Hr(),
        html.Div(id='display-selected-values'),
    ]
)


@app.callback(
    Output('cities-radio', 'options'), Input('countries-radio', 'value')
)
def set_cities_options(selected_country):
    return [{'label': i, 'value': i} for i in all_options[selected_country]]


@app.callback(Output('cities-radio', 'value'), Input('cities-radio', 'options'))
def set_cities_value(available_options):
    return available_options[0]['value']


@app.callback(
    Output('display-selected-values', 'children'),
    Input('countries-radio', 'value'),  # 라디오버튼의 값
    Input('cities-radio', 'value'),
)
def set_display_children(selected_country, selected_city):
    return u'{} is a city in {}'.format(
        selected_city,
        selected_country,
    )


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

Tags:

Categories:

Updated: