Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วาง Legend Symbol แบบกำหนดเองใน Matplotlib

สร้าง custom handler โดยสืบทอด HandlerPatch และ override create_artists

ตัวอย่างโค้ด


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()

ผลลัพธ์

Legend แสดงเป็น Ellipse แทน Circle ตามที่กำหนด

วาง Legend Symbol แบบกำหนดเองใน Matplotlib