Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Hiển thị phân phối song biến (bivariate distribution) với imshow trong Matplotlib

Phân phối song biến mô tả xác suất liên hợp của hai biến ngẫu nhiên. imshow hiển thị ma trận 2D như hình ảnh (heatmap).

Cài đặt

pip install matplotlib

Ví dụ: Hai phân phối Gaussian 2D chênh lệch


import numpy as np
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
from matplotlib.path import Path
from matplotlib.patches import PathPatch

np.random.seed(9654241)
delta = 0.025
x = y = np.arange(-4.5, 4.5, delta)
X, Y = np.meshgrid(x, y)

Z1 = np.exp(-X**2 - Y**2)           # Gaussian tâm (0,0)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)  # Gaussian tâm (1,1)
Z = (Z1 - Z2) * 2                   # Hiệu hai Gaussian

fig, ax = plt.subplots()
plt.title('Phân phối song biến (Bivariate Distribution)')
plt.xlabel('x-axis')
plt.ylabel('y-axis')
im = ax.imshow(Z, interpolation='bilinear', origin='lower',
               extent=[-3, 3, -3, 3],
               vmax=abs(Z).max(), vmin=-abs(Z).max())
plt.show()

Kết quả

Hiển thị phân phối song biến (bivariate distribution) với imshow trong Matplotlib

Giải thích

  • Tạo hai Gaussian 2D, lấy hiệu → phân phối có vùng dương/âm.
  • imshow với interpolation='bilinear' làm mượt.
  • origin='lower' gốc tọa độ góc dưới bên trái.
  • extent ánh xạ pixel -> dữ liệu.
  • vmax/vmin cân bằng thang màu quanh 0.

Ứng dụng: Trực quan hóa posterior, likelihood, residual heatmap.