본문 바로가기
industry/해외기업산업분석

구글 코랩에서 트리맵(treemap) 차트를 만드는 방법

by Peter Choi 2025. 1. 29.
반응형

주로 산업의 비율이나 포트폴리오의 구성을 시각화할 때 여러 개의 사각형을 붙여놓은 듯한 차트가 자주 보입니다. 이러한 차트를 트리맵 차트라고 합니다. 

위와 같이 산업군별로 비중이 큰 기업부터 주가의 등락폭을 큰 크기의 사각형으로 나타내는 사례로 알 수 있죠.

 

이러한 차트를 만드는 방법에는 다양한 방법이 있습니다만, 파이썬과 코랩을 이용해서 만드는 방법을 소개합니다.

 

https://github.com/laserson/squarify 

 

GitHub - laserson/squarify: Pure Python implementation of the squarify treemap layout algorithm

Pure Python implementation of the squarify treemap layout algorithm - laserson/squarify

github.com

공식 깃허브 주소입니다.

 

코드는 아래와 같습니다. 참고로 저는 홍콩의 산업별 분포를 나타내었습니다.

 

!pip install squarify
 
#폰트 다운로드 및 깨짐 설정
!sudo apt-get install -y fonts-nanum
!sudo fc-cache -fv
!rm ~/.cache/matplotlib -rf
 
import matplotlib.pyplot as plt
plt.rc('font', family='NanumBarunGothic')
 
import matplotlib.pyplot as plt
import squarify

# Data for the treemap
labels = ['무역 및 물류업', '금융 서비스업', '전문 서비스 및 비즈니스 지원업', '관광업', '기타 산업']
sizes = [21.5, 18.9, 12.2, 4.5, 42.9]

# Combine labels with sizes
labels_with_sizes = [f'{label}\n({size}%)' for label, size in zip(labels, sizes)]

# Colors for the treemap
colors = ['#ff9999','#66b3ff','#99ff99','#ffcc99','#c2c2f0']

# Create the treemap
plt.figure(figsize=(12, 8))
squarify.plot(sizes=sizes, label=labels_with_sizes, color=colors, alpha=0.8, bar_kwargs={'linewidth': 5, 'edgecolor': 'white'})
plt.title('홍콩의 산업별 비율 (2023년 기준)')
plt.axis('off')

# Save the treemap as an image file
plt.savefig("hongkong_industry_treemap.png")

# Display the treemap
plt.show()

 

이렇게 결과물이 나오게 됩니다. 섹터별 간격이나 두 줄 쓰기등은 위의 코드에서 추가적으로 파라미터를 추가한 부분입니다. 

 

반응형

댓글