Các bước
- Thiết lập kích thước hình và padding.
- Khởi tạo biến
N cho số mẫu.
- Tạo dữ liệu
x, y, c, s bằng numpy.
- Tạo figure và subplots.
- Vẽ.scatter với màu và kích thước khác nhau.
- Đặt legend cho lớp (classes) bằng
legend_elements().
- Thêm artist vào figure.
- Tạo legend cho kích thước (sizes).
- 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ả
