import matplotlib.pyplot as pltimport numpy as npnp.random.seed(42)data = np.random.normal(170, 10, 1000) # 키 데이터fig, axes = plt.subplots(1, 3, figsize=(15, 4))# bin 수에 따른 차이for ax, bins in zip(axes, [10, 30, 100]): ax.hist(data, bins=bins, color='#4a9eca', edgecolor='white', alpha=0.8) ax.set_title(f'bins={bins}') ax.set_xlabel('키 (cm)') ax.set_ylabel('빈도')plt.suptitle('히스토그램 — bin 크기의 영향', fontsize=14)plt.tight_layout()plt.show()
Copy
# 밀도 히스토그램 + KDE 곡선fig, ax = plt.subplots(figsize=(8, 5))ax.hist(data, bins=30, density=True, color='#4a9eca', edgecolor='white', alpha=0.7, label='히스토그램')# KDE 곡선 추가from scipy import statsx_range = np.linspace(data.min(), data.max(), 100)kde = stats.gaussian_kde(data)ax.plot(x_range, kde(x_range), color='#e6a23c', linewidth=2, label='KDE')ax.set_title('키 분포 (밀도)')ax.legend()plt.tight_layout()plt.show()
Sturges’ Rule(bins = 1 + log2(n)), Scott’s Rule, Freedman-Diaconis Rule 등이 있습니다. Matplotlib에서 bins='auto'를 사용하면 자동으로 적절한 값을 선택합니다. 일반적으로 20~50 사이가 적절합니다.