본문 바로가기
데이터 처리/빅데이터 분석 (Big data) in Python

matplotlib 히스토그램, Seaborn 시각화

by Jun_N 2020. 1. 5.

 

 

히스토그램

: 도수분포를 그래프로 나타낸것. 데이터의 형상과 산포 정도를 평가하는데 많이 사용한다.

  

pyplot.hist() #히스토그램을 그리는 함수

 

1. 히스토그램 그리기

plt.figure(figsize=(12,7))
plt.his(value,label=['1st','2nd'],bins=30) #bins는 데이터를 구간으로 나누는 개수이다.

plt.grid(True)
plt.legend(bbox_to_anchor=(1.2, 1),loc="upper right")
# bbox_to_anchor는 라벨의 상대적인 위치를 잡아주는 옵션(x축,y축으로 각각 이동)


 

 

 

 

 

2. 히스토그램 색 입히기 - 데이터 셋 별로 다른 색 입히기

plt.his(value,label=['1st','2nd'],bins=30,color=(yellow, green)

 

 

 

3. 각 patch에 다른 색 입히기

 

for 문과 setp()함수를 사용하면 된다.

 

value=np.random.standard_normal(500) #난수 500개 생성, 2줄의 배열 value 변수 할당
cm=plt.cm.get_cmap('Spectral') #Spectral이라는 이름의 컬러맵을 cm변수로 할당( 0~ 1 RGBA값)
plt.figure(figsize=(12,6))

#plot histogram
n, bins, patches=plt.hist(value,bins=30,color='green')
print("1 bins: " + str(binns)) #총 31개 edge
print("2 the length of bins: " + str(len(bins)))


 

patch에 색을 입히기 전에 히스토그램 각 bin들의 중간값을 구한 다음에 값들을 0~1 사이의 값으로 범위를 좁히는 작업이 필요하다.

 

bin_centers= 0.5 * (bins[:-1] + bins[1:]) # 첫번째 ~마지막 요소 전 + 두번째 ~ 마지막 = 중간값

#scale values to interval[0,1] : 정규화 ( 값들을 0 ~ 1사이 값으로 바꾸는 과정)
#새로운 값 = (현재값-최소값) / (최대값 - 최소값)
col=(bins_centers - min(bin_centers)) / (max(bin_centers)-min(bin_centers))

for c, p in zip(col, patches):
	plt.setp(p,'facecolor',cm(c)) #cm(c)는 각 패치의 색
   
  

 

 

 

 

 

 

 

 

 

Seaborn

: Matplotlib를 기반으로 통계적 그래픽을 제공하는 고차원 인터페이스 제공. python 시각화 패키지

(heatmap: 색상으로 표현할 수 있는 정보를 열 분포 형태로 나타낸 그래프)

 

'flights' 데이터로 heatmap 그리기

 

1. Seaborn 내장 데이터셋 'flights' 로드

 

data2=sns.load_dataset('flights') #Seaborn 라이브러리 내장 데이터셋인 'flight' 가져오기

#2. 데이터 pivot

pivot_data=data2.pivot('year','month','passengers') 

#3. heatmap
sns.set(context='poster',font='monospace')
sns.heatmap(pivot_data,annot=True,fmt='d',linewidth=3) 
#annot은 히트맵의 각 셀에 데이터의 값 표시할 것인지 설정
#fmt가 d이면 10진수

 

 

 

 

 

 

 

 

#파이썬을 이용한 빅데이터 분석 ㅣ 유성준 교수님 자료 참고