Để vẽ biểu tượng chú giải tùy chỉnh trên một biểu đồ, chúng ta có thể thực hiện các bước sau -
- Đặt kích thước hình và điều chỉnh phần đệm giữa và xung quanh các ô phụ.
- Kế thừa HandlerPatch lớp, ghi đè phương thức tạo nghệ sĩ, thêm một bản vá hình elip vào cốt truyện và trả về trình xử lý bản vá.
- Vẽ một vòng tròn trên lô đất bằng cách sử dụng Vòng tròn lớp học.
- Thêm một bản vá hình tròn trên trục hiện tại.
- Sử dụng chú giải () phương pháp đặt chú giải vào cốt truyện.
- Để hiển thị hình này, hãy sử dụng show () phương pháp.
Ví dụ
import matplotlib.pyplot as plt, matplotlib.patches as mpatches
from matplotlib.legend_handler import HandlerPatch
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
class HandlerEllipse(HandlerPatch):
def create_artists(self, legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans):
center = 0.5 * width - 0.5 * xdescent, 0.5 * height - 0.5 * ydescent
p = mpatches.Ellipse(xy=center, width=width + xdescent, height=height + ydescent)
self.update_prop(p, orig_handle, legend)
p.set_transform(trans)
return [p]
c = mpatches.Circle((0.5, 0.5), 0.25, facecolor="green", edgecolor="red", linewidth=1)
plt.gca().add_patch(c)
plt.legend([c], ["An ellipse,Customized legend element"],
handler_map={mpatches.Circle: HandlerEllipse()})
plt.show() Đầu ra