Histogram แสดงการกระจายตัวของข้อมูลตัวเลข (Numerical Distribution) โดยแบ่งเป็น Bins และนับความถี่
Seaborn ใช้ distplot() (Deprecated) หรือ histplot() / displot(kind='hist') (แนะนำ) สำหรับ Histogram
ตัวอย่างโค้ด (distplot - เก่า)
import pandas as pd
import seaborn as sb
from matplotlib import pyplot as plt
df = sb.load_dataset('iris')
sb.distplot(df['petal_length'], kde=False)
plt.show()
ผลลัพธ์

คำอธิบาย
โหลดข้อมูล Iris
distplot(data, kde=False)แสดง Histogram เท่านั้น (kde=False ปิด KDE)
วิธีใหม่แนะนำ: histplot() / displot()
import seaborn as sns
import matplotlib.pyplot as plt
df = sns.load_dataset('iris')
# 1. histplot - แสดงบน Axes เดียว
sns.histplot(data=df, x='petal_length', bins=20, kde=False)
plt.title("Petal Length Histogram")
plt.show()
# 2. displot - Figure-level (แยก Figure เอง)
sns.displot(data=df, x='petal_length', kind='hist', bins=20)
plt.show()
# 3. แยกตาม Hue (Species)
sns.histplot(data=df, x='petal_length', hue='species', multiple='stack', bins=20)
plt.show()
# 4. กำหนด Bin Edges เอง
import numpy as np
bins = np.linspace(0, 7, 15)
sns.histplot(data=df, x='petal_length', bins=bins)
plt.show()
พารามิเตอร์สำคัญ histplot/displot
| พารามิเตอร์ | คำอธิบาย |
|---|---|
| bins | จำนวน Bin หรือ Array ของ Bin Edges |
| binwidth | ความกว้าง Bin (แทน bins) |
| binrange | (min, max) ของ Bin Range |
| kde | True/False - วาด KDE ทับ Histogram |
| stat | 'count', 'frequency', 'density', 'probability' |
| multiple | 'layer', 'dodge', 'stack', 'fill' (สำหรับ Hue) |
| element | 'bars', 'step', 'poly' (รูปแบบ Bar) |
การเลือกจำนวน Bins
# Rules of thumb
# Sturges: log2(n) + 1
# Rice: 2 * n**(1/3)
# Scott: 3.5 * std / n**(1/3)
# Freedman-Diaconis: 2 * IQR / n**(1/3)
# Seaborn ใช้ 'auto' (Max of Sturges และ Freedman-Diaconis)
sns.histplot(data, bins='auto')