본문 바로가기
DataScience/Matplotlip

Matplotlip 히스토그램, 갯수범위지정, bins, subplot

by leopard4 2022. 11. 28.

# 구간을 설정하여, 해당 구간에 포함되는 데이터가 몇개인지(갯수)
# 세는 차트를 히스토그램이라고 한다.
# 구간을, bin 이라고 부른다.
# 구간이 여러개니까, bins 라고 부른다.
# 히스토그램은, 똑같은 데이터를 가지고,
# bin을 어떻게 잡느냐에 따라서, 차트 모양이 달라져서, 
# 해석을 다르게 할 수 도있다.

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

 

plt.hist(data = df, x = 'speed')
plt.show()

# bins 의 갯수는 기본이 10개(디폴트값)
plt.hist(data = df, x = 'speed', rwidth= 0.8)
plt.show()

# bins 의 갯수를 변경하는 방법
plt.hist(data = df, x = 'speed', rwidth= 0.8, bins = 30)
plt.show()

# bin 의 범위값을 지정하는 경우
# 스피드를 3단위로, 5단위로, 11단위로, 13단위로 ....... 해라
# 최대값과 최소값을 뽑은 후에, 그범위안에서, 단위를 생성해준다.
df['speed'].min()
5

df['speed'].max()
160

np.arange(5, 160+1)
array([  5,   6,   7,   8,   9,  10,  11,  12,  13,  14,  15,  16,  17,
        18,  19,  20,  21,  22,  23,  24,  25,  26,  27,  28,  29,  30,
        31,  32,  33,  34,  35,  36,  37,  38,  39,  40,  41,  42,  43,
        44,  45,  46,  47,  48,  49,  50,  51,  52,  53,  54,  55,  56,
        57,  58,  59,  60,  61,  62,  63,  64,  65,  66,  67,  68,  69,
        70,  71,  72,  73,  74,  75,  76,  77,  78,  79,  80,  81,  82,
        83,  84,  85,  86,  87,  88,  89,  90,  91,  92,  93,  94,  95,
        96,  97,  98,  99, 100, 101, 102, 103, 104, 105, 106, 107, 108,
       109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121,
       122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134,
       135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147,
       148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160])
       
my_bins = np.arange(5, 160+7, 7)

plt.hist(data = df, x = 'speed', rwidth= 0.8, bins = my_bins)
plt.show()

Figures, Axes and Subplots

# 하나에 차트영역에 여러개의 plot을 그린다.

plt.figure(figsize = (12, 5))  # figsize = 가로세로 비율

plt.subplot(1 ,2 , 1)  # 1행,2열,1번째

plt.title("speed hist. bins 10")
plt.xlabel("Speed")
plt.ylabel("# of Characters")

plt.hist(data = df, x = 'speed', rwidth= 0.8)

plt.subplot(1, 2 , 2) # 1행,2열,2번째

plt.title("speed hist. bins 30")
plt.xlabel("Speed")
plt.ylabel("# of Characters")


plt.hist(data = df, x = 'speed', rwidth= 0.8, bins =30)

plt.show()