[우리FISA 5기] AI엔지니어링 3주차 - 011일차

이정환·2025년 7월 15일

우리FISA

목록 보기
9/12

011일차 - Plotly

Plotly란?

  • 반응형 / 오픈소스 / 브라우저 기반 파이썬 시각화 라이브러리 이다.
  • 시각화 결과를 상호작용 가능한 HTML 파일로 저장할 수 있다.
  • matplotlib와 다르게 기본적으로 한글 폰트 지원

🔗Plotly | Graphing Libararies
🔗Python API reference for plotly

Plotly 기본 구조 🔗[데이터 시각화] Plotly 사용법 - ZERO

  • Figure: Plotly의 기본 시각화 단위
  • data: 시각화 대상이 되는 데이터
  • layout: data와 무관한 편집요소, ex) Title, Line, Box,...

시각화 방식 세 가지

  • Python Dictionary 이용
  • GO(Graphic Objects) 이용
  • plotly.express 모듈 이용

🔗Python Day 13_PLOTLY(반응형 그래프) - rocki.log

dict

  • Python Dictionary 자료형을 사용하여 data, layout에 대한 정보로 시각화 할 수 있다.
import plotly.io as pio
fig = dict({ # Python Dictionary 자료형 이용
    "data": [{"type": "bar",
              "x": [1, 2, 3],
              "y": [1, 3, 2]}],
    "layout": {"title": {"text": "딕셔너리로 그린 그래프"}}
})

pio.show(fig)

go

  • Plotly의 기본 시각화 단위인 Figure를 생성한다.
  • 기본적인 틀 생성 후 Figure에 대한 추가적인 커스터마이징이 가능하다.

🔗Graph Objects in Python - plotly

import pandas as pd

df = pd.DataFrame({
  "Fruit": ["Apples", "Oranges", "Bananas", "Apples", "Oranges", "Bananas"],
  "Contestant": ["Alex", "Alex", "Alex", "Jordan", "Jordan", "Jordan"],
  "Number Eaten": [2, 1, 3, 1, 3, 2],
})

# Graph Objects
import plotly.graph_objects as go

# Figure 인스턴스 생성
fig = go.Figure()

# 세부 설정 적용
for contestant, group in df.groupby("Contestant"):
    fig.add_trace(go.Bar(x=group["Fruit"], y=group["Number Eaten"], name=contestant,
      hovertemplate="Contestant=%s<br>Fruit=%%{x}<br>Number Eaten=%%{y}<extra></extra>"% contestant))
fig.update_layout(legend_title_text = "Contestant")
fig.update_xaxes(title_text="Fruit")
fig.update_yaxes(title_text="Number Eaten")
fig.show()

express

  • Figure를 대상으로 추가적인 설정을 적용한 시각화 함수들을 제공한다.
  • 추가적인 설정 없이 Figure 생성 시 인자를 입력하여 조금 더 빠르고 간결하게 시각화 할 수 있다.
import plotly.express as px

# 데이터 할당
tips = px.data.tips()

fig1 = px.그래프명(
    tips,           # 시각화 대상 데이터(데이터프레임 형식)
    x='tip',        # x축에 들어갈 컬럼
    y='total_bill', # y축에 들어갈 컬럼
    color='sex',    # 색상 구분 기준이 될 컬럼명 (seaborn의 hue와 같은 역할)
    size='tip',     # tip 에 따라 크기를 변화
    marginal_x = 'box',       # scatterplot의 옵션 중 하나인 인접 그래프의 스타일 지정 (박스) 
    marginal_y = 'histogram', # scatterplot의 옵션 중 하나인 인접 그래프의 스타일 지정 (히스토그램) 
    trendline="ols",          # x축과 y축으로 지정된 데이터에 대해서 회귀분석(ols로)
    trendline_color_override="grey",  # trendline 색상 지정
    hover_name='day',                 # 팝업 데이터 최상단에 위치할 데이터프레임의 컬럼명
    hover_data=['day', 'size'],       # 마우스 호버 시 참고할 데이터 추가 - tips.columns로 설정하면 다 보여줌 
    title='Tips by Total Bill - Scatter Plot', # 그래프 타이틀 지정
    facet_col='day', # day 기준으로 분할
    width=800,       # 그래프의 크기 조절
    height=600
) 
fig1.show()

로그 스케일

  • 데이터의 값과 시각화 그래프의 축에 상용로그를 씌우는 것
  • 값에 로그를 취하게 되면 값이 작아진다. log(x)<xRlog(x) < x \in \mathbb{R}
  • 로그를 취한 결과의 차이는 상대적인 비율을 나타낸다. (밑 기준 지수값 의미)
  • 데이터의 구간이 넓은 경우 로그 스케일로 변경하여, 작은 차이를 상대적으로 크게 확인할 수 있다.
  • 시각화의 목적은 데이터의 특징을 파악하는 것이기 때문

🔗왜 로그 스케일을 사용하는가? - 딥상어동의 딥한생각

%와 %p의 차이

  • 퍼센트(%)는 상대적인 크기 의미
  • 퍼센트 포인트(%p)는 절대적인 크기 차이 의미

캔들 차트 시각화

  • 주가의 OHLC 정보가 있다면 go.CandleStick으로 캔들 차트를 시각화할 수 있다.

🔗Candlestick Charts in Python - plotly


import pandas as pd
import yfinance as yf

# Yahoo Finance API Library 이용
pltr = yf.download('PLTR',
                   start='2024-01-01',
                   end='2025-07-15',
                   progress=False)

# datetime 인덱스를 컬럼으로
pltr.reset_index(inplace=True, drop=False)

# 멀티 인덱스에서 Date, OHLCV로 단일 차원화
pltr.columns = [name for name, ticker in pltr.columns]

# 캔들 차트 시각화
import plotly.graph_objects as go

fig = go.Figure(data=[
    go.Candlestick(
        x=pltr['Date'],
          open=pltr['Open'],
          high=pltr['High'],
          low=pltr['Low'],
          close=pltr['Close']
    )
])

fig.show()

plotly.figure_factory

  • plotly의 go만으로 시각화하기 어려운 종류의 시각화 함수를 모아둔 모듈
  • express 등장 이전에 사용되었다.
  • legacy로 남겨져 있다.
  • express에는 distplot이 없기 때문에 figure_factory 모듈에서 사용한다.

템플릿 적용

  • 이미 제작된 색 템플릿을 사용할 수 있다.
  • express에서 시각화 함수 호출 시 template인자로 문자열 전달
  • ex) 'ggplot2', 'plotly'
# 사용가능한 템플릿 출력
pio.templates

# 기본으로 적용되는 템플릿 변경
pio.templates.default = "seaborn"

scatter_geo 지도 시각화

  • 제공되는 지도에 산점도를 시각화할 수 있다.

🔗Scatter Plots on Maps in Python - plotly
🔗plotly.express.scatter_geo - API Docs

import plotly.express as px

# 2007년 gapminder 데이터 불러오기
df = px.data.gapminder().query("year == 2007")

# scatter_geo Figure 인스턴스 생성
fig = px.scatter_geo(df, locations="iso_alpha",
                     color="continent", # which column to use to set the color of markers
                     hover_name="country", # column added to hover information
                     size="pop", # size of markers
                     projection="natural earth")
fig.show()

pd.DataFrame category 자료형

  • pd.DataFrame의 특정 컬럼이 범주형인 경우 String(혹은 object) 자료형으로 되어 있다면 메모리가 낭비된다.
  • category형으로 변경해준다면 각 원소별 문자열을 개별로 저장하는 것이 아니라 값을 참조하는 형식으로 변경되어 메모리가 절약된다.
df.astype('category')

🔗카테고리/범주 데이터(categorical dtype) 순서/레벨 적용하기 - Clary K

0개의 댓글