Skip to main content

Plotly 심화

Plotly의 고급 기능을 활용하면 애니메이션으로 시간 변화를 표현하고, 서브플롯으로 여러 차트를 결합하며, Dash 프레임워크로 인터랙티브 대시보드를 구축할 수 있습니다.

학습 목표

  • make_subplots로 여러 차트를 하나의 Figure에 배치할 수 있다
  • animation_frame으로 시간 변화 애니메이션을 만들 수 있다
  • facet_col/facet_row로 조건별 차트를 자동 생성할 수 있다
  • Dash의 기본 개념을 이해한다

왜 중요한가

데이터의 시간적 변화, 그룹별 비교, 다차원 분석을 효과적으로 전달하려면 정적 차트를 넘어선 표현이 필요합니다. 인터랙티브 대시보드는 비즈니스 의사결정자가 직접 데이터를 탐색할 수 있게 해줍니다.

서브플롯

from plotly.subplots import make_subplots
import plotly.graph_objects as go
import pandas as pd
import numpy as np

# 서브플롯 생성
fig = make_subplots(rows=1, cols=2,
                    subplot_titles=['매출 추이', '부서별 비중'])

# 왼쪽: 선 그래프
dates = pd.date_range('2024-01-01', periods=30, freq='D')
fig.add_trace(
    go.Scatter(x=dates, y=np.cumsum(np.random.randn(30)) + 100,
               name='매출', line=dict(color='#4a9eca')),
    row=1, col=1
)

# 오른쪽: 파이 차트
fig.add_trace(
    go.Pie(labels=['개발', '영업', '마케팅'], values=[45, 30, 25],
           marker_colors=['#4a9eca', '#4a9e4a', '#e6a23c']),
    row=1, col=2
)

fig.update_layout(title='종합 대시보드', height=400)
fig.show()

애니메이션

import plotly.express as px

# 시간에 따른 변화 애니메이션
np.random.seed(42)
years = range(2020, 2025)
data = []
for year in years:
    for dept in ['개발', '영업', '마케팅']:
        data.append({
            'year': year,
            'department': dept,
            'headcount': np.random.randint(20, 60),
            'revenue': np.random.randint(100, 500)
        })

anim_df = pd.DataFrame(data)

fig = px.scatter(anim_df, x='headcount', y='revenue',
                 color='department', size='revenue',
                 animation_frame='year',
                 range_x=[10, 70], range_y=[50, 550],
                 title='부서별 인원-매출 변화')
fig.show()

facet — 조건별 차트

np.random.seed(42)
df = pd.DataFrame({
    'value': np.random.randn(300),
    'group': np.repeat(['A', 'B', 'C'], 100),
    'category': np.tile(['X', 'Y'], 150)
})

# 열 방향 facet
fig = px.histogram(df, x='value', facet_col='group',
                   color='category', title='그룹별 분포')
fig.show()

# 행+열 facet
fig = px.histogram(df, x='value', facet_col='group', facet_row='category',
                   title='그룹 x 카테고리별 분포')
fig.show()

Dash 소개

# Dash는 Plotly 기반의 웹 대시보드 프레임워크입니다
# pip install dash

# 기본 구조 예시 (실행 코드)
"""
from dash import Dash, html, dcc
import plotly.express as px

app = Dash(__name__)

df = px.data.iris()
fig = px.scatter(df, x='sepal_width', y='sepal_length', color='species')

app.layout = html.Div([
    html.H1('Iris 데이터 탐색'),
    dcc.Graph(figure=fig)
])

if __name__ == '__main__':
    app.run_server(debug=True)
"""
Dash는 별도의 프론트엔드 지식 없이 Python만으로 웹 대시보드를 구축할 수 있습니다. 데이터 분석 결과를 팀과 공유하거나, 실시간 모니터링 대시보드를 만들 때 유용합니다.

AI/ML에서의 활용

  • 실험 추적: 애니메이션으로 epoch별 모델 성능 변화를 시각화합니다
  • 하이퍼파라미터 탐색: facet으로 각 하이퍼파라미터 조합의 결과를 비교합니다
  • 모델 모니터링: Dash로 실시간 모델 성능 대시보드를 구축합니다
  • 결과 보고: 인터랙티브 차트로 비기술자에게 분석 결과를 전달합니다
JupyterLab에서는 별도 설정 없이 동작합니다. 클래식 Jupyter Notebook에서는 fig.show(renderer='notebook') 또는 plotly.offline.init_notebook_mode(connected=True)를 사용하세요.

체크리스트

  • make_subplots로 서브플롯을 구성할 수 있다
  • animation_frame으로 시간 변화 애니메이션을 만들 수 있다
  • facet_col/facet_row로 조건별 차트를 생성할 수 있다
  • Dash의 기본 개념과 활용 시나리오를 이해한다

다음 문서