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

Cách thêm legend cho imshow() trong Matplotlib


Vì imshow() không hỗ trợ legend trực tiếp, bạn vẽ các đường giả (proxy artists) với màu tương ứng để thêm vào legend.

  • Tạo dữ liệu ngẫu nhiên, colormap.
  • Lấy giá trị duy nhất từ dữ liệu.
  • Vẽ các điểm ẩn với màu từ colormap, gán label.
  • Gọi plt.legend().
  • Cuối cùng gọi imshow().

Ví dụ minh họa

import numpy as np
from matplotlib import pyplot as plt, cm

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

data = np.random.rand(3, 3)
cmap = cm.YlOrBr
unique_data = np.unique(data)
i = 0
for entry in unique_data:
    mycolor = cmap(entry * 255 / (max(unique_data) - min(unique_data)))
    plt.plot(0, 0, "-", color=mycolor, label="%d"%i)
    i += 1
plt.imshow(data, cmap=cmap)
plt.legend(loc="upper right", bbox_to_anchor=(1.25, 1.0))
plt.show()

Kết quả đầu ra

Cách thêm legend cho imshow() trong Matplotlib