ภาพรวม
Rug Plot แสดงการกระจายของข้อมูล 1 มิติ โดยวาดเส้นเล็ก (tick marks) ตามแกน มักใช้ร่วมกับ Density Plot (KDE)
ขั้นตอนการทำงาน
- Import numpy, scipy.stats, matplotlib.pyplot
- สร้างข้อมูล x
- คำนวณ Kernel Density Estimate (KDE) 2 แบบ: Scott's Rule และ Silverman's Rule
- สร้าง figure และ axes
- วาด Rug plot:
ax.plot(x, np.zeros_like(x), 'b+', ms=20) - วาดเส้น KDE ทั้งสองแบบ
- เพิ่ม Legend และแสดงผล
ตัวอย่างโค้ด
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.array([-6, -4, 2, 1, 4], dtype=np.float)
kde1 = stats.gaussian_kde(x)
kde2 = stats.gaussian_kde(x, bw_method='silverman')
fig = plt.figure()
ax = fig.add_subplot(111)
# Rug plot
ax.plot(x, np.zeros(x.shape), 'b+', ms=20)
x_eval = np.linspace(-5, 5, num=100)
ax.plot(x_eval, kde1(x_eval), 'k-', label="Scott's Rule")
ax.plot(x_eval, kde2(x_eval), 'r-', label="Silverman's Rule")
plt.legend(loc='upper right')
plt.show()
ผลลัพธ์
Rug plot (เครื่องหมาย + สีน้ำเงิน) ตามแกน X พร้อมเส้น KDE 2 แบบ

ตัวเลือกอื่น
- Seaborn:
sns.rugplot(data=x)ทำได้ใน 1 บรรทัด - ร่วมกับ
sns.kdeplot()หรือsns.histplot(kde=True) - Matplotlib 3.4+ มี
ax.axvline()หรือax.eventplot()สำหรับ rug plot