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

Cách vẽ bản đồ mật độ (density map) trong Python Matplotlib

Dùng pcolormesh để vẽ mật độ 2D từ hàm Gaussian.

  • side = linspace(-2,2,15).
  • X, Y = meshgrid(side, side).
  • Z = exp(-((X-1)² + Y²)).
  • plt.pcolormesh(X, Y, Z, shading='auto').
  • show().

Ví dụ

from matplotlib import pyplot as plt, cm, colors
import numpy as np
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
side = np.linspace(-2, 2, 15)
X, Y = np.meshgrid(side, side)
Z = np.exp(-((X - 1) ** 2 + Y ** 2))
plt.pcolormesh(X, Y, Z, shading='auto')
plt.show()

Kết quả

Density map (heatmap) Gaussian tâm tại (1,0) trên lưới 15x15.