Python/Matplotlib

Matplotlib) Histograms(히스토그램) 차트 그리기

567Rabbit 2024. 4. 15. 18:01

 

- 주어진 각 구간 내에 위치하는 관측치 수를 보여주는 그래프이다

- 빈도 분포를 보여주는 그래프이다
- 일정한 해당 구간에 포함되는 데이터의 분포를 알 수 있다

- 일정 구간을 bin이라고 하며 구간이 여러개면 복수형으로 bins라고 한다

- 히스토그램은 똑같은 데이터를 가지고 bin을 어떻게 설정하느냐에 따라서 차트모양이 달라지며 해석이 달라진다

 

 

 

df

  id species hp attack defense speed
0 1 bulbasaur 45 49 49 45
1 2 ivysaur 60 62 63 60
2 3 venusaur 80 82 83 80
3 4 charmander 39 52 43 65
4 5 charmeleon 58 64 58 80
... ... ... ... ... ... ...
802 803 poipole 67 73 67 73
803 804 naganadel 73 73 73 121
804 805 stakataka 61 131 211 13
805 806 blacephalon 53 127 53 107
806 807 zeraora 88 112 75 143

 

 

plt.hist(data=df,x='speed', rwidth=0.9, bins = 20)
plt.show()

 

# rwidth는 막대의 너비를 뜻하며, 0.9로 설정하면 막대의 폭이 전체 가로폭의 90%를 차지하게 된다

# bins의 개수는 기본이 10개 구간이다. 이 구간의 갯수를 설정할 수 있다

 

 

# 구간의 범위를 직접 설정하려면, 데이터의 최소값, 최대값을 알아야 한다

df['speed'].describe()
count    807.000000
mean      65.830235
std       27.736838
min        5.000000
25%       45.000000
50%       65.000000
75%       85.000000
max      160.000000
Name: speed, dtype: float64

 

 

my_bins = np.arange(5,160+5,5)

 

plt.hist(data=df,x='speed', rwidth=0.9, bins = my_bins )
plt.savefig('hist2.png')
plt.show()

 

 

Subplots

-한번에 여러개의 그래프를 보여준다

 

plt.figure( figsize = (12, 5) ,  ) 
# figsize 매개변수는 그래프 전체의 총 사이즈를 조절할 수 있다. 
# 두 그래프가 들어가므로 가로 사이즈를 넓게 하였다

plt.subplot(1, 2, 1)
plt.hist(data=df, x='speed', rwidth=0.9 )
plt.title('speed hist. bins 10')
plt.xlabel('Speed')
plt.ylabel('# of Characters')

plt.subplot(1, 2, 2)
plt.title('speed hist. bins 20')
plt.xlabel('Speed')
plt.ylabel('# of Characters')

plt.hist(data=df,x='speed', rwidth=0.9, bins = 20)

plt.show()