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

Cách lấy đối tượng colorbar từ figure trong Matplotlib

Tạo colorbar từ đối tượng imshow (scalar mappable) và gán vào biến.

  • Tạo dữ liệu ngẫu nhiên 10x10 giá trị -1 đến 1.
  • im = plt.imshow(data, interpolation="nearest").
  • cbar = plt.colorbar(im).
  • show().

Ví dụ

import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
data = np.random.randint(-1, 1, (10, 10))
im = plt.imshow(data, interpolation="nearest")
cbar = plt.colorbar(im)
plt.show()

Kết quả

Ảnh 10x10 với colorbar bên phải, đối tượng colorbar lưu trong biến cbar.