'heatmap by python seaborn'에 해당되는 글 1건

  1. 2019.01.19 [Python] 히트맵 그리기 (Heatmap by python matplotlib, seaborn, pandas) 1

이번 포스팅에서는 X축과 Y축에 2개의 범주형 자료의 계급(class)별로 연속형 자료를 집계한 자료를 사용하여, 집계한 값에 비례하여 색깔을 다르게 해서 2차원으로 자료를 시각화하는 히트맵(Heatmap)을 그려보겠습니다. 


기본적인 Python 라이브러리를 importing 하였으며, matplotlib, seaborn, pandas 의 순서대로 히트맵 그리는 방법을 소개하겠습니다. 



import numpy as np

import pandas as pd


import matplotlib.pyplot as plt

import seaborn as sns

plt.rcParams['figure.figsize'] = [10, 8]

 




예제로 사용할 데이터는 연도(year)별 월(month)별 승객 수(passengers)를 모아놓은 flights 라는 seaborn에 내장되어 있는 데이터프레임입니다. 



flights = sns.load_dataset('flights')


flights.head()

yearmonthpassengers
01949January112
11949February118
21949March132
31949April129
41949May121

 




pivot() 함수를 이용하여 월별 연도별 승객수를 집계한 피벗 테이블(pivot table)을 만들어서, 이를 이용해서 이어서 히트맵을 그려보겠습니다. 



df = flights.pivot('month', 'year', 'passengers')


df.head()

year194919501951195219531954195519561957195819591960
month
January112115145171196204242284315340360417
February118126150180196188233277301318342391
March132141178193236235267317356362406419
April129135163181235227269313348348396461
May121125172183229234270318355363420472

 




  (1) matplotlib을 이용한 히트맵 그리기 (Heatmap by matplotlib)


plt.pcolor() 함수를 이용하여 히트맵을 그리고, plt.colorbar() 로 색상에 대한 정보를 오른쪽에 제시해줍니다. 



# heatmap by plt.pcolor()

plt.pcolor(df)

plt.xticks(np.arange(0.5, len(df.columns), 1), df.columns)

plt.yticks(np.arange(0.5, len(df.index), 1), df.index)

plt.title('Heatmap by plt.pcolor()', fontsize=20)

plt.xlabel('Year', fontsize=14)

plt.ylabel('Month', fontsize=14)

plt.colorbar()


plt.show()




  (2) seaborn을 이용한 히트맵 그리기 (Heatmap by seaborn)


seaborn은 데이터가 2차원 피벗 테이블 형태의 DataFrame으로 집계가 되어 있으면 sns.heatmap() 함수로 매우 간단하게 히트맵을 그려줍니다. 



# heatmap by seaborn

ax = sns.heatmap(df)

plt.title('Heatmap of Flight by seaborn', fontsize=20)

plt.show() 




이번에는 annot=True argument를 써서 각 셀에 숫자를 입력(annotate each cell with numeric value)하여 보겠습니다. fmt='d' 는 정수 형태(integer format)로 숫자를 입력하라는 뜻입니다. 



# annotate each cell with the numeric value of integer format

sns.heatmap(df, annot=True, fmt='d')

plt.title('Annoteat cell with numeric value', fontsize=20)

plt.show()





cmap 에 색깔을 다르게 설정해보겠습니다. 

(color maps in Matplotlib 에 대한 자세한 설명은 다음 링크를 참고하세요 ==> https://matplotlib.org/3.2.1/tutorials/colors/colormaps.html )



# different colormap

sns.heatmap(df, cmap='RdYlGn_r')

plt.title('colormap of cmap=RdYlGn_r', fontsize=20)

plt.show()




히트맵의 색깔을 cmap='YIGnBu' 로 설정해서 파란색과 노란색 계열로 바꾸어보겠습니다. 



# different colormap

sns.heatmap(df, cmap='YlGnBu') # 

plt.title('colormap of cmap=YlGnBu', fontsize=20)

plt.show()




색깔 지도(color map)의 중심을 1949년 1월(January)으로 맞추어서 히트맵을 그려보겠습니다. 좌측 최상단이 1949년 1월 (1949 January) 로서 히트맵 색의 중심 위치가 되었습니다. 



# center the colormap at a specific value

sns.heatmap(df, center=df.loc['January', 1949])

plt.title('Center the colormap at Jan. 1949', fontsize=20)

plt.show()





  (3) pandas를 이용한 히트맵 그리기 (Heatmap by pandas)


pandas는 df.style.background_gradient(cmap='summer')를 사용해서 DataFrame에 숫자에 따라서 직접 색을 다르게 입힐 수 가 있습니다. 마치 엑셀에서 피벗 테이블한 다음에 숫자에 따라서 색을 다르게 입히는 것과 유사하게요. 



# heatmap by pandas

df.style.background_gradient(cmap='summer')



이상으로 Python으로 히트맵 그리기를 마치겠습니다. 

많은 도움이 되었기를 바랍니다. 


이번 포스팅이 도움이 되었다면 아래의 '공감~'를 꾹 눌러주세요. :-)



728x90
반응형
Posted by Rfriend
,