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

Hiển thị np.array bằng pylab.imshow() trong Matplotlib

Để hiển thị mảng NumPy 2D như một ảnh, dùng plt.imshow() với colormap và interpolation.

Các bước

  • Thiết lập figure size và autolayout.
  • Tạo mảng 2D data = np.array([[...]]).
  • Hiển thị: plt.imshow(data, interpolation="nearest", cmap="RdYlGn_r").
  • Hiển thị bằng show().

Ví dụ

import numpy as np
from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

data = np.array([[0.1, 0.7, 0.6, 0.3], [0.2, 0.6, 0.5, 0.2], [0.8, 0.3, 0.80, 0.01], [0.3, 0.4, 0.2, 0.1]])
plt.imshow(data, interpolation="nearest", cmap="RdYlGn_r")
plt.show()

Kết quả

Hiển thị np.array bằng pylab.imshow() trong Matplotlib