🔗Plotly | Graphing Libararies
🔗Python API reference for plotly
Plotly 기본 구조
🔗[데이터 시각화] Plotly 사용법 - ZERO
🔗Python Day 13_PLOTLY(반응형 그래프) - rocki.log
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)
🔗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()
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()
🔗왜 로그 스케일을 사용하는가? - 딥상어동의 딥한생각
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'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')