Để vẽ biểu tượng legend tùy chỉnh trên đồ thị, ta thực hiện:
- Thiết lập kích thước hình và điều chỉnh khoảng đệm giữa và xung quanh subplots.
- Kế thừa class HandlerPatch, ghi đè phương thức create artists, thêm elliptical patch vào đồ thị, trả về patch handler.
- Vẽ hình tròn trên đồ thị dùng class Circle.
- Thêm circle patch vào trục hiện tại.
- Dùng legend() đặt legend trên đồ thị.
- Hiển thị hình dùng show().
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()
Kết quả
