ในการพล็อตสัญลักษณ์คำอธิบายที่กำหนดเองบนโครงเรื่อง เราสามารถทำตามขั้นตอนต่อไปนี้ -
- กำหนดขนาดรูปและปรับช่องว่างภายในระหว่างและรอบๆ แผนผังย่อย
- รับค่า HandlerPatch คลาส แทนที่เมธอด create artist เพิ่มแพตช์วงรีให้กับพล็อต และส่งคืนตัวจัดการแพตช์
- วาดวงกลมบนโครงเรื่องโดยใช้ วงกลม คลาส.
- เพิ่มแพทช์วงกลมบนแกนปัจจุบัน
- ใช้ legend() วิธีการวางตำนานบนโครงเรื่อง
- หากต้องการแสดงรูป ให้ใช้ show() วิธีการ
ตัวอย่าง
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() ผลลัพธ์
