Để gán nhãn cho patch (hình chữ nhật, ellipse, polygon...) trong Matplotlib:
- Thiết lập kích thước figure và padding
- Khởi tạo tâm hình chữ nhật patch
- Tạo figure mới
- Thêm
axvào figure - Thêm
rectanglevào axes patches; trả vềpatch - Đặt legend trên figure
- Hiển thị bằng
show()
Ví dụ mã nguồn
import matplotlib.pyplot as plt import matplotlib.patches as patches plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True x = y = 0.1 fig = plt.figure() ax = fig.add_subplot(111) patch = ax.add_patch(patches.Rectangle((x, y), 0.5, 0.5, alpha=0.5, facecolor='red', label='Rectangle')) plt.legend(loc='upper right') plt.show()
Kết quả
Hình chữ nhật đỏ bán trong suốt tại (0.1, 0.1) kích thước 0.5x0.5, legend hiển thị "Rectangle".

Các patch phổ biến: Rectangle, Circle, Ellipse, Polygon, Arrow, FancyBboxPatch. Tất cả đều hỗ trợ tham số label cho legend.