Python의 matplotlib 라이브러리를 이용해 데이터를 시각화 할 때 boxplot이 많이 사용된다. 특히, 이 boxplot은 데이터의 분포에 대한 통계 정보를 포함해 그릴수 있다는 장점이 있다.
2021.05.03 - [Programming/Machine Learning] - Seaborn boxplot으로 five-number summary 이해하기
2020.11.02 - [Programming/Tips] - [seaborn] 그림의 폰트 사이즈 바꾸기
이 포스팅에서 boxplot의 그림을 더 보기 좋게 꾸미는 방법, 특히, 박스별 다르게 색을 지정하는 것에 대해서 정리해 보았다.
Table of Contents
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from IPython.display import Image
data = np.random.normal(0.1, size=(100,9))
data[:,0:3] = data[:,0:3] + 3
data[:,6:] = data[:,6:] - 3
plt.figure(figsize=(10,3))
_ = plt.boxplot(data)
boxplot¶
박스별 다른 색 적용하기¶
우선 matplotlib에서 제공하는 컬러의 이름을 알아보자. List of named colors of Matplotlib에서 확인할 수 있다. 아래 사진에서 보듯이 다양한 컬러가 있다.
display(Image(filename='/Users/Shared/color_named.png', width=800))
이중에 tableau palette 컬러 9개를 골라 colors라는 리스트를 만든다
colors = ['tab:blue',
'tab:brown',
'tab:green',
'tab:red',
'tab:purple',
'tab:pink',
'tab:olive',
'tab:cyan',
'tab:gray']
아래와 같이 boxplot을 적용해서 각 박스를 다른 색으로 그릴 수 있다.
plt.figure(figsize=(12,3))
for i, c in enumerate(colors):
_ = plt.boxplot(data[:,i],
labels=[c], # <---- 박스의 컬러를 x축의 이름으로 출력한다
positions=[i], # <---- x축 상의 박스의 위치를 지정한다.
widths = 0.5, # <---- 박스의 폭을 조절한다.
vert = True, # <---- 박스를 수식으로 그리도록 한다
patch_artist=True, # <---- 박스의 속성을 바꿀 수 있도록 설정한다
boxprops=dict(facecolor=c, color='k'), # <- 박스의 face와 가장자리 색을 지정
medianprops=dict(color='k') # <--- 중간값 선의 색 지정
)
_ = plt.xticks(rotation=60, fontsize=13)
_ = plt.yticks(fontsize=13)
_ = plt.ylabel("numbers", fontsize=13)
plt.grid(color='grey', linestyle='-', linewidth=0.5, axis='y')
그룹별로 다르게 색 지정하기¶
이번에는 박스를 그룹별로 색을 다르게 그리는 방법을 해보자. 총 9개의 박스가 있으니, 편의상 세 그룹이 있다고 가정해보자. 그럼 총 3개의 색이 필요하다. 우선 data를 그룹별로 나누는 slice와 위치를 지정하는 position 리스트를 만든다.
groups,positions = [], []
group_size = 3
i, end = 0, 0
while end < data.shape[1]:
groups.append(slice(end, end+group_size))
positions.append([*range(end,end+group_size)])
end = end+group_size
i+=1
for i, (g, p) in enumerate(zip(groups, positions)):
print("group {}: {}, {}".format(i, g, p))
group 0: slice(0, 3, None), [0, 1, 2]
group 1: slice(3, 6, None), [3, 4, 5]
group 2: slice(6, 9, None), [6, 7, 8]
plt.figure(figsize=(12,3))
for i, r in enumerate(groups):
_ = plt.boxplot(data[:,r],
positions=positions[i],
labels=[colors[i]]*group_size,
widths=0.4,
vert = True,
patch_artist=True,
boxprops=dict(facecolor=colors[i], color=colors[i]),
medianprops=dict(color='k'))
_ = plt.xticks(rotation=60, fontsize=13)
_ = plt.yticks(fontsize=13)
_ = plt.ylabel("numbers", fontsize=13)
plt.grid(color='grey', linestyle='-', linewidth=0.5, axis='y')
적용하면 그룹별 다른 색이 적용된 것을 볼 수 있다.
x축의 박스 라벨도 색 이름대로 지정되었다.
'Programming > Tips' 카테고리의 다른 글
M1 맥북에 native PyTorch 설치하기 (conda 환경) (0) | 2021.10.16 |
---|---|
[M1 맥북] GPU에서 tensorflow 실행하기 (tensorflow 2.5 설치) (7) | 2021.08.15 |
[Jupyter notebook] Table of Contents (TOC) 넣기 (상단/사이드 배치) (2) | 2021.05.30 |
[Arm64] M1 맥북에 tensorflow 2.4 설치하기 (conda 환경) (1) | 2021.04.27 |
[Jupyter notebook] 코드 접기 (codefolding) 설정하기 (0) | 2021.04.19 |
댓글