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

Tự động tạo chú thích (legend) trong Matplotlib


Các bước

  1. Thiết lập kích thước hình và padding.
  2. Khởi tạo biến N cho số mẫu.
  3. Tạo dữ liệu x, y, c, s bằng numpy.
  4. Tạo figure và subplots.
  5. Vẽ.scatter với màu và kích thước khác nhau.
  6. Đặt legend cho lớp (classes) bằng legend_elements().
  7. Thêm artist vào figure.
  8. Tạo legend cho kích thước (sizes).
  9. Gọi show().

Ví dụ

import matplotlib.pyplot as plt
import numpy as np

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

N = 45
x, y = np.random.rand(2, N)
c = np.random.randint(1, 5, size=N)
s = np.random.randint(10, 220, size=N)

fig, ax = plt.subplots()
scatter = ax.scatter(x, y, c=c, s=s)

legend1 = ax.legend(*scatter.legend_elements(), loc="lower left", title="Classes")
ax.add_artist(legend1)

handles, labels = scatter.legend_elements(prop="sizes", alpha=0.6)
legend2 = ax.legend(handles, labels, loc="upper right", title="Sizes")
plt.show()

Kết quả

Tự động tạo chú thích (legend) trong Matplotlib