Developer/web

Dash - graph plotting method

hadaney 2020. 5. 25. 14:24

Dash is an open-source Python framework used for building analytical web applications

Dash는 (분석 시각화를 위한 또는 대시보드에 특화된) 웹 어플리케이션을 빌드하는데 사용되는 파이썬 프레임웤 오픈소스다.

 

오늘은 Dash의 여러 기능 중 dcc.Graph component에 초점을 두어 얘기해 보기로 하자.

 

The dcc.Graph component can be used to render any plotly-powered data visualization, passed as the figure argument.

dcc.Graph 모듈은 plotly (python grpahing library)로 생성한 figure 를 받아들여 웹상에 표현해줍니다.

ploty를 잘 알고있다면 쉽겠죠? 그런 의미에서 이 포스팅은 plotly 기능들에 대한 이야기가 주가 될 것 같습니다.

 

1. Plotly Express in Dash

The fig object is passed directly into the figure property of dcc.Graph

plotly 라이브러리를 이용해서 figure를 생성하여 dcc.Graph에 넘겨준다.

 

import dash_core_components as dcc
import plotly.express as px

# 1) 데이터를 부르고
df = px.data.iris() # iris is a pandas DataFrame

# 2) plotly를 통해 graph figure를 만들어서
fig = px.scatter(df, x="sepal_width", y="sepal_length")

# 3) dash의 component로 넘긴다
dcc.Graph(figure=fig)

 

2. Using the Low-Level interface3 with go.Figure

1번과 다른 점은 plotly.express가 아닌 graph_object를 직접 호출하여 compnent를 만들었다는 점이다.

간단히 정리하면

 - Plotly Express 는 tidy or long data(pd.DataFrame or array-like object such as list, np.array, pd.Series)를 받아서 graph object를 리턴한다

 - 바로 graph_object 를 사용한다는 것은 data나 plot을 직접적으로 명시하여 figure를 구성하겠다는 뜻

import dash_core_components as dcc
import plotly.graph_objs as go

# 1) 데이터를 하나하나 입력한다.
fig = go.Figure(data=[go.Scatter(x=[1, 2, 3], y=[4, 1, 2])])

# 2) dcc.Graph 에 component로 보낸다
dcc.Graph(
        id='example-graph-2',
        figure=fig
    )

 

3. Using the Low-level Interface with Dicts & Lists

Dash로 plot을 그릴때 필자가 가장 많이 이용하는 방법이다.

plotly를 이용해 figure를 미리 구성하여 넘기지 않고, dictionary 형태로 정의만 하여 graph를 생성하는 방법

굳이 plotly 를 import 하지 않아도 Dash가 dictionary 정보로부터 알아서 plot을 구성한다

import dash_core_components as dcc
dcc.Graph(
        id='example-graph',
        
        # figure를 미리 구성하여 인자로 넘기지 않고, dictionary 형태로 표현하여 넘겨준다.
        figure={
            'data': [
                {'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'SF'},
                {'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': u'Montréal'},
            ],
            'layout': {
                'title': 'Dash Data Visualization'
            }
        }
    )

-> figure에 dictionary를 넘겨줄때 각각의 key와 그 의미를 이해하고 싶다면, plotly의 figure reference를 참고하면 된다.

https://plotly.com/python/reference/ 

 

이상 Dash의 plotting 방식 설명 끝!