본문 바로가기
머신러닝/Model Evaluation

Python Box plot

by 미생22 2024. 4. 27.
728x90

+모양이 평균지점이고 Box plot의 맨 위와 맨 아래가 upper fence, lower fence입니다.

데이터의 절반이 들어가는 IQR(Interquartile Range)의 각각 1.5배를 벗어나는 지점에 만약 데이터가 있으면 이 데이터를 outlier라고 말합니다.

 

samples = [1, 7, 9, 16, 36, 39, 45, 45, 46, 48, 51, 100, 101]
samples

tmp_y = [1]*len(samples)
tmp_y

 

당연히 두 개의 길이는 똑같습니다.

len(samples), len(tmp_y)

이제 이걸 가지고 plot을 그릴겁니다.

 

import matplotlib.pyplot as plt

plt.figure(figsize=(12,4))
plt.scatter(samples, tmp_y)
plt.grid()
plt.show()

 

이 데이터에서 각 지표를 찾아보겠습니다.

중간값 (median)은

import numpy as np

np.median(samples)

45가 나오구요,

25% 지점 즉 Q1은 

np.percentile(samples,25)

16이 나오구요,

 75%지점 즉 Q3는 

np.percentile(samples,75)

48이 나오네요.

 

이제 IQR를 구해보겠습니다.

np.percentile(samples,75) - np.percentile(samples,25) #IQR

32가 나오네요.

 

outlier를 찾기위해 IQR의 1.5배가 되는 수치를 알아보면,

iqr = np.percentile(samples,75) - np.percentile(samples,25)
iqr*1.5

48이 나오는 것을 확인했습니다.

 

이제 iqr 및 25%, 75% 지점에 line을 그려보겠습니다.

q1 = np.percentile(samples,25)
q2 = np.median(samples)
q3 = np.percentile(samples,75)

iqr = q3 - q1

upper_fence = q3 + iqr*1.5
lower_fence = q1 - iqr*1.5
plt.figure(figsize=(12,4))
plt.scatter(samples, tmp_y)

#upper fence와 lower fence를 그려보겠습니다.

plt.axvline(x=q1, color='black')
plt.axvline(x=q2, color='red')
plt.axvline(x=q3, color='black')
plt.axvline(x=upper_fence, color='black', ls='dashed')
plt.axvline(x=lower_fence, color='black', ls='dashed')


plt.show()

 

outlier 2개가 코딩을 통해 찾을 수 있다는 사실을 알 수 있습니다. 그러나 seaborn이 제공하는 boxplot에서 다 확인할 수 있습니다 :D

728x90