[DASH] Plotly Application Chart
Box Plot
Box Plot 기본 구문
trace = go.Box(y = 수치형 값)
data = [trace]
layout = go.Layout(디자인 옵션)
fig = go.Figure(data, layout)
fig.show()
Box Plot 예시
데이터 설명
Column : Region(지역), Revenue(매출)
2020년 지역별로 매출 데이터를 담은 df
대륙별 매출액 분포 비교 Box Plot
traces = []
for region in regions:
tmp = df_g[df_g['Region']==region]
traces.append(go.Box(y=tmp['Revenue'],
name = region))
data = traces
layout = go.Layout(title ='Chapter 3.1 - Box Plot')
fig = go.Figure(data,layout)
fig.show()
Histogram
Histogram 기본 구문
trace = go.Histogram(x = 수치형 값)
data = [trace]
layout = go.Layout(디자인 옵션)
fig = go.Figure(data, layout)
fig.show()
make_subplot() 기본 구문
from plotly.subplots import make_subplots
fig = make_subplot(rows = 행의 수, cols = 열의 수, shared_yaxes = options)
data = [trace1, trace2, ... ]
fig.append_trace( ..., rows, cols)
fig.append_trace(data[0], 1, 1)
fig.append_trace(data[1], 1, 2)
fig.update_layout(디자인 옵션)
fig.show()
이때, option에 따라 공유되는 y값이 달라짐
options | 내용 |
---|---|
True | 동일한 row(행) 내의 처음 그려진 그래프의 y축 값을 공유 |
‘columns’ | 동일한 column(열) 내의 처음 그려진 그래프의 y축 값을 공유 |
‘all’ | 모든 그래프가 처음 그려진 그래프의 y축값을 공유 |
Histogram 예시
데이터 설명
Column : AgeGroup(연령대), Quantity(수량)
연령대와 수량이 작성되어있는 데이터 df
연령대별 구매수량 분포 비교
from plotly.subplots import make_subplots
fig = make_subplots(rows = 2, cols =3, shared_yaxes = 'all')
trace = []
for age in ages:
trace.append(go.Histogram(x=df_g[df_g['AgeGroup']==age]['Quantity'], name = age))
fig.append_trace(trace[0],1,1)
fig.append_trace(trace[1],1,2)
fig.append_trace(trace[2],1,3)
fig.append_trace(trace[3],2,1)
fig.append_trace(trace[4],2,2)
fig.update_layout(title = 'Chapter 3.2 - Histogram')
fig.show()
Error Bar
Error Bar 기본 구문
trace = go.Chart(x = 값,
y = 수치형 값,
error_y = dict(type = 'data',
array = 차이값),
text = 텍스트)
data = [trace]
layout = go.Layout(디자인 옵션)
fig = go.Figure(data, layout)
fig.show()
Error Bar 예시
데이터 설명
Column : Channel(채널), year(연도), mean(평균), sd(표준편차), n(개수), lower(최소값), upper(최대값), text(평균값(하한값, 상한값))
Offline 연도별 매출액 분포 비교 Error Bar
df_g2 = df_g1[df_g1['Channel']=='Offline'].copy()
trace = go.Scatter(x = df_g2['year'],
y = df_g2['mean'],
error_y = dict(type = 'data',
array = df_g2['sd']),
name = 'Offline')
data = [trace]
layout = go.Layout(title = 'Chapter 3.3 - Scatter & Error Bar (Offline)',
xaxis = dict(title = 'Year'),
yaxis = dict(title = 'Revenue (Mean)'))
fig = go.Figure(data, layout)
fig.show()
Online/Offline 연도별 매출액 분포 비교 Error Bar
channels = list(df_g1['Channel'].unique())
traces = []
for channel in channels:
dat = df_g1[df_g1['Channel']== channel]
traces.append(go.Bar(x=dat['year'],
y=dat['mean'],
error_y = dict(type = 'data',
symmetric=False,
array = dat['sd']
),
text = dat['text'],
hoverinfo = 'text',
name = channel))
data = traces
layout = go.Layout(title = 'Chapter 3.3 - Scatter & Error Bar (Offline)',
xaxis = dict(title = 'Year'),
yaxis = dict(title = 'Revenue (Mean)',
range = [0,ymax]))
fig = go.Figure(data,layout)
fig.show()
Rader Chart
Rader Chart 기본 구문
trace = go.Scatterpolar(r = 평가점수,
theta = 평가항목,
fill = 'toself')
data = [trace]
layout = go.Layout(디자인 옵션)
fig = go.Figure(data, layout)
fig.show()
Rader Chart 예시
데이터 설명
Column : year(연도), Category(상품), Revenue(매출), Rank(순위)
매출 구간별로 Rank라는 순위 변수를 부여(10000000 미만, 10000000 이상 ~ 30000000 미만, 30000000 이상 ~ 50000000 미만, 50000000 이상 ~ 70000000 미만, 70000000 이상)
2020년도 상품 매출액 순위 비교 Rader Chart
ranks = list(d20['Rank'])
ranks.append(ranks[0])
thetas = list(d20['Category'])
thetas.append(thetas[0])
trace = go.Scatterpolar(r = ranks,
theta = thetas,
fill = 'toself',
name = '2020')
data = [trace]
layout = go.Layout(title = 'Chapter 3.4 - Rader Chart')
fig = go.Figure(data, layout)
fig.show()
연도별 상품 매출액 순위 - Rader Chart
years = list(df_g['year'].unique())
years.sort()
traces = []
for year in years:
dat = df_g[df_g['year'] == year]
ranks = list(dat['Rank'])
ranks.append(ranks[0])
thetas = list(dat['Category'])
thetas.append(thetas[0])
traces.append(go.Scatterpolar(r = ranks,
theta = thetas,
name = year))
data = traces
layout = go.Layout(title = 'Chapter 3.4 - Rader Chart',
legend_orientation = 'h',
legend = dict(x = 0.3, y = -0.1))
fig = go.Figure(data, layout)
fig.show()
Indicator
Indicator 기본 구문
trace = go.Indicator(mode = option, # 출력모드
value = 수치형 값, # 주요값
number = dict(옵션), # 주요값 형식 설정
delta = dict(옵션), # 차이값 입력 및 형식 설정
gauge = dict(옵션), # 데이지 형식 설정
domain = dict(옵션) # 출력 범위 설정
)
data = [trace]
layout = go.Layout(디자인 옵션)
fig = go.Figure(data, layout)
fig.show()
Indicator 예시
Indicator 기본 예제
import pandas as pd
import numpy as np
import plotly.graph_objects as go
trace1 = go.Indicator(value = 200,
delta = dict(reference = 160),
gauge = dict(axis = dict(visible = False)),
domain = dict(row = 0, column = 0))
trace2 = go.Indicator(value = 120,
gauge = dict(shape = 'bullet'),
domain = dict(x = [0.05, 0.5], y = [0.15,0.35]))
trace3 = go.Indicator(mode = 'number+delta',
value = 300,
domain = dict(row=0, column =1))
trace4 = go.Indicator(mode = 'delta',
value = 40,
domain = dict(row = 1, column = 1))
data = [trace1, trace2, trace3, trace4]
layout = go.Layout(grid = {'rows':2, 'columns':2, 'pattern':'independent'},
template = {'data':{'indicator':
[{'title': {'text':'Speed'},
'mode':'number+delta+gauge',
'delta':{'reference':90}}]}})
fig = go.Figure(data,layout)
fig.show()
데이터 설명
매출, 이익 합계 산출 데이터
매출 및 이익 총계 비교
values = df_g1['Revenue']
deltas = df_g1['Revenue']-df_g1['Margin']
trace = go.Indicator(mode = 'number+delta', # 출력방식
value = values, # 주요값 입력
number = dict(prefix='$', # 주요값 앞 문자열
suffix = 'M', # 주요값 뒤 문자열
valueformat = ',0f'), # 값 형식
delta = dict(reference = deltas, # 차이값 입력
valueformat = '.2f', # 값 형식
relative = False,
increasing = dict(color = 'blue'), # 증가 시 색상
position = 'top')) # 차이값 위치
data = [trace]
layout = go.Layout(title = 'Chapter 3.5 - Indicator',
paper_bgcolor = 'white') # 배경 흰색
fig = go.Figure(data,layout)
fig.show()
Maps
Bubble Map
Bubble Map 기본 구문
trace = go.Scattergeo(lon = 경도,
lat = 위도,
mode = 'markers',
marker = dict(symbol = 'circle',
size = 크기))
data = [trace]
layout = go.Layout(디자인 옵션,
geo = dict(scope = 'world',
showcountries = True))
fig = go.Figure(data, layout)
fig.show()
Bubble Map 예시
데이터 설명
Column : Country(국가), Revenue(매출), Longitude(경도), Latitude(경도), Code3(국가 코드)
hover text를 위한 text column도 만들어줌 (형식 : 국가명 - Total Revenue : 매출액 (단위: M))
국가별 매출 총계 비교 - Bubble Map
trace = go.Scattergeo(lat = df_g2['Latitude'], # 위도
lon = df_g2['Longitude'], # 경도
mode = 'markers', # 산점도
marker = dict(symbol = 'circle', # 원형
size = np.sqrt(df_g2['Revenue']/10000)),
text = df_g2['text'], # hover text 활성화
hoverinfo = 'text') # 입력한 text만 활성화
data = [trace]
layout = go.Layout(title = 'Chapter 3.6 - Bubble Maps',
geo = dict(scope = 'world',
projection_type = 'equirectangular',
showcountries = True)) # 국가 경계선
fig = go.Figure(data,layout)
fig.show()
Choropleth Map
Choropleth Map 기본 구문
trace = go.Choropleth(locations = 영역의 국가 코드,
z = 영역 내 수치형 값)
data = [trace]
layout = go.Layout(디자인 옵션,
geo = dict(scope = 'world',
showcountries = True))
fig = go.Figure(data, layout)
fig.show()
Choropleth Map 예시
국가별 매출 총계 비교 - Choropleth Map
trace = go.Choropleth(locations = df_g2['Code3'], # 국가 코드
z = df_g2['Revenue'], # 영역 내 표현 값
colorscale = 'Blues', # 영역 색상
reversescale = True, # 컬러바 scale 반대
marker_line_color = 'darkgray', # 영역 테두리 색상
marker_line_width = 0.5, # 영역 테두리 두께
colorbar_tickprefix = '$', # 컬러바 축 문자열
colorbar_title = 'Revenue US$') # 컬러바 제목
data = [trace]
layout = go.Layout(title = 'Chapter 3.6 - Choropleth Maps',
geo = dict(scope = 'world',
projection_type = 'equirectangular',
showframe = False, # 지도 테두리
showcoastlines = False)) # 해양 경계선
fig = go.Figure(data,layout)
fig.show()
댓글남기기