
Youtube 이수안컴퓨터연구소의
Plotly 한번에 끝내기 - 모던한 인터렉티브 시각화 라이브러리 동영상을 보고 요약한 코드입니다!
import plotly.io as pio
import plotly.express as px
import plotly.graph_objects as go
import plotly.figure_factory as ff
from plotly.subplots import make_subplots
from plotly.validators.scatter.marker import SymbolValidator
# -- templates options --
pio.templates
# go.Scatter
fig = go.Figure()
config = {
# 'scrollZoom' : True/False,
# 'displayModeBar' : True/False,
# 'editable' : True/False, # 수정 직접 가능
# 'displaylogo' : True/False,
# 'displaylogo' : True/False,
# 'responsive' : True/False,
# 'staticPlot' : True/False, # hover 인포 안보여줌 -> 고정이 되버림
}
fig.add_trace(go.Scatter(
x=, y=,
mode = , # markers, lines, markers+lines
text = , # 컬럼 정보 사용 가능
textposition = , # middle right/..
marker = dict(
size = ,
# *** color ***
color = , # 컬럼 정보 사용 가능
colorscale = , # YlOrRd/Inferno/[] (리스트) ..., 대신 color 부분도 변경 --> color_continuous_scale 역할
colorbar = dict(
title =,
tickvals = [],
ticktext = []
),
cmax = , cmin = , # colorscale 최대/최소
showscale = , # True -> 옆에 컬러바 보여줌
),
# *** legends ***
name = , # legend에 보일 이름
visible = , # legendonly:초기 설정 안보이게
legendgroup = , # legend 그룹화
))
fig.show(
# config = config
)
# px.scatter
fig = px.scatter(
data, x=, y=,
mode = ,
color = , # data['column'].astype(str) or .astype(float) 으로도 색깔 변경 가능
color_continuous_scale = , # px.colors.sequential.Viridis / Inferno /
# 리스트로도 가능 : ['red', 'blue] / [(0, 'red'), (0.3, 'green'), (1, 'blue')]
range_color = , # ex) [2,6] : 숫자로 color scale 만듬
symbol = ,
size = ,
size_max = ,
log_x = , log_y = , # True/False -> fig.update_layout, go. X
range_x = [,], range_y = [,],
template = , # template
title = ,
facet_col = , facet_row = , #
width = , height = ,
labels = {}, # label 바꾸기
hover_data = [], # .index 사용 가능
)
fig.show()
# -- fig.update_layout ------------------------------------------
fig.update_layout(
# *** title ***
title = dict(
text = ,
x = , y = , # text position
xanchor = , yanchor = , # center/top
),
# *** axis (axes) ***
yaxis = dict( # OR xaxis
side = , # top/bottom
# *** title ***
title = dict(
text = ,
font = dict(
size = , # title_font_size
family = ,
color =
),
standoff = , # 축에서의 거리
),
# *** tick formatting ***
showgrid = , # True/False
zeroline = , # True/False
zerolinewidth = , zerolinecolor = , # zeroline 설정
linewidth = , linecolor = , # 축 설정
gridwidth = , gridcolor = , # 안에 그리드 설정
mirror = ,
ticktext = ,
tickangle = ,
tickvals = [], # 축 정보 강제 입력 (고정)
tickmode = , # array/linear
tickformat = '', # %, %Y-%b-%d(%a)
showexponent = , # all
exponentformat = , # e -> 지수로 표기법 변경
tick0 = , # 초기 tick값
dtick = , # tick 간격
# *** range/scale ***
range = [,],
constrain = , # domain : 압축되게
fixedrange = , # True/False
scaleanchor = , # x/y : 고정 비율 (확대를 할 때 고정이 되버림),
scaleratio = , # 1
autorange = , # reversed: 축반전 OR range = [9,3]
rangemode = , # nonnegative/tozero
type = , # log/category
),
# *** legends ***
showlegend = , # True/False
legend = dict(
yanchor = , xanchor = , # top/bottom/left/right
y = , x = , # 1.. (숫자)
orientation = , # h/v
itemsizing = , # constant
),
# *** colorscale/colorbar ***
coloraxis_colorbar = dict(
title = ,
tickvals = [],
ticktext = []
),
# *** others, yet essential ***
height = , width = ,
showlegend = , # True/False
template = ,
autosize = , # True/False
margin = dict( # margin
l = ,
r = ,
t = ,
b = ,
pad =
),
paper_bgcolor = ,
)
# -- fig.update_axes ------------------------------------------
fig.update_xaxes( # OR yaxes
# *** title ***
title = dict(
text = ,
font = dict(
size = ,
family = , # Courier/
color =
)
)
# *** tick formatting ***
showgrid = , # True/False
zeroline = , # True/False
zerolinewidth = , zerolinecolor = , # zeroline 설정
linewidth = , linecolor = , # 축 설정
gridwidth = , gridcolor = , # 안에 그리드 설정
mirror = , # 4방면 축라인에 모두 적용
showticklabels = , # True/False
ticks = , # outside/inside
col = , # 숫자에 따라 어느 자리에 tick이 올건지 결정 1~
nticks = , # grid의 수 (tick 수) 결정
tickson = , # boundaries
ticklen = ,
tickvals = [], # 축 값 강제 고정 (입력)
tickwidth = ,
tickcolor = ,
tickangle = ,
tickfont = dict(
family = , # Arial/..
color = ,
size =
)
dtick = , # tick distance
# *** rangeslider ***
rangeslider_visible = , # True/False
# *** range ***
range = [,],
fixedrange = , # True/False , 축 zoom X
constrain = , # domain : 압축되게
scaleanchor = , # x/y : 고정 비율 (확대를 할 때 고정이 되버림),
scaleratio = , # 1
autorange = , # reversed : 축반전
rangemode = , # nonnegative/tozero
type = , # log/category
# *** other, yet essential ***
automargin = , # True/False
side = , # top/bottom/left/right
)
# -- fig.update_traces ------------------------------------------
fig.update_traces(
# *** scatter plots styling **
mode = , # markers
marker = dict(
size = ,
symbol = ,
color = ,
cmax = , cmin = ,
line = dict(
width = ,
color =
),
colorbar = dict(
title =,
tickvals = [],
ticktext = []
),
colorscale = , # 리스트/Inferno..
showscale = , # True/False
),
selector = dict(
mode = , # markers
name = , # fig.add_trace의 name = / 특정 부분만 선택하여 update 가능
),
opacity = ,
hovertemplate = ,
)
fig.show()
# -- text/annotation/hover/spikes ------------------------------------------
# text/hover/spikes
fig = px.scatter(
data, x=, y=,
# *** hover ***
hover_name = ,
hover_data = []
)
fig.update_traces(
# *** text ***
textposition = , # top center(scatter)/outside(bar)
texttemplate = , # ex) '%{text:.2s}'
# *** hover ***
hovertemplate = , # None/ ex) 'GDP : %{x} <br>Life Expectancy: %{y}'
selector = {}
)
fig.update_xaxes( # OR _yaxes
# *** spikes ***
showspikes =, # True/False
spikecolor = ,
spikesnap = , # cursor
spikemode = , # across
spikethickness =
)
fig.update_layout(
# *** hover ***
hovermode = , # x/y
hoverlabel = dict(
bgcolor = ,
font_size = ,
font_familty = , # Courier New
),
hoverdistance =
# *** spikes ***
spikedistance = ,
)
fig.show()
# annotation
fig = go.Figure()
fig.add_trace(go.Scatter(
x =, y=
))
fig.add_trace(go.Scatter(
x =, y=
))
fig.add_annotation(
x=, y=, # annotation 위치
xref = , yref =, # 'x', 'y', 'paper'
text = ,
showarrow = , # True/False
font = dict(
family = , # Courier New, monospace
size = ,
color =
),
align = , # center/..
# *** arrow ***
arrowhead = ,
arrowsize = ,
arrowwidth = ,
arrowcolor = ,
# *** annotation ***
bordercolor = ,
borderwidth = ,
borderpad = ,
bgcolor = ,
opacity =
)
fig.add_annotation(
x=, y=,
text = ,
)
fig.update_annotations(
dict(
xref = , # 'x'
yref = , # 'y'
showarrow = , # True/False
arrowhead = , # arrow 종류 (int)
ax = , ay = , # arrow 각도(방향)
)
)
fig.update_layout(
showlegend = False
)
fig.show()
# -- multipls axes/subplots ------------------------------------------
fig = make_subplots(
rows =, cols =,
subplot_titles = (), # 소제목
specs = [[{'secondary_y' : True}], [{}], # type : xy/polar/domain(pie chart)/scene(3d chart)
[{}], [{}], ..], # secondary_y, secondary_x : True/False
# colspan (rowspan) : 2/None : column or row 확장
start_cell = , # 시작 위치 : bottom-left/bottom-right/..
column_width = [], # 공간 비율 ex) [0.7, 0.3]
shared_xaxes = , share_yaxes = , # 축 공유 True/False
vertial_spacing = , # 그래프 간의 거리
)
fig.add_trace(go.Scatter(
x =, y =,
name = ,
marker = dict(
color = ,
coloraxis = , # coloraxis
)
), row =, col =, secondary_y = )
fig.add_trace(go.Scatter(
x =, y =,
name = ,
), row =, col =, secondary_y = )
fig.add_trace(go.Scatter(
x =, y =,
name = ,
), row =, col =, secondary_y = )
# *** fig.update_[xy]axes ***
fig.update_xaxes(
title_text = ,
row=, col= # row, col 정보에 따라 다르게
)
fig.update_xaxes(
title_text = ,
range=,
row=, col=
)
fig.update_yaxes(
title_text = ,
showgrid=,
row=, col=
)
# *** fig.update_layout ***
fig.update_layout(
height = ,
width = ,
coloraxis = dict(
colorscale = , # ylgn
),
showlegend = , # True/False
)
fig.show()
# -- multiple chart types --
# 단순히 차트 추가
fig = go.Figure()
fig.add_trace(go.Scatter())
fig.add_trace(go.Bar())
fig.show()
# -- color scales --
fig = px.colors.sequential.swatches()
# fig = px.colors.diverging.swatches()
# fig = px.colors.colors.cyclical.swatches()
# fig = px.colors.qualitative.swatches()
fig.show()