ใช้ HandlerTuple รวม Marker หลายตัวให้อยู่ภายใต้ Legend Entry เดียวกัน สำหรับกรณีที่มีเส้นหลายเส้นแทน Label เดียวกัน
ขั้นตอน
- ตั้งค่าขนาด Figure
- สร้างข้อมูล X และ 4 เส้นโค้ง (2 เส้น sin, 2 เส้น cos)
- Plot แต่ละเส้นพร้อม Label ซ้ำกัน
- ใช้
HandlerTupleรวม Handler ใน Legend - แสดงผล
ตัวอย่างโค้ด
import numpy as np
from matplotlib import pyplot as plt, legend_handler
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(-10, 10, 100)
# 2 เส้น sin(x) สไตล์ต่างกัน
c1, = plt.plot(x, np.sin(x), ls='dashed', label='y=sin(x)')
c2, = plt.plot(x, np.sin(x+0.25), ls='dashdot', label='y=sin(x)')
# 2 เส้น cos(x) สไตล์ต่างกัน
c3, = plt.plot(x, np.cos(x), ls='solid', label='y=cos(x)')
c4, = plt.plot(x, np.cos(x+0.25), ls=':', label='y=cos(x)')
# รวม Handler: (c1,c2) -> 'y=sin(x)', (c3,c4) -> 'y=cos(x)'
plt.legend([(c1, c2), (c3, c4)], ['y=sin(x)', 'y=cos(x)'],
loc='upper right',
handler_map={tuple: legend_handler.HandlerTuple(ndivide=None)})
plt.show()
คำอธิบาย
[(c1, c2), (c3, c4)]: กลุ่ม Handler ที่ต้องการรวม['y=sin(x)', 'y=cos(x)']: Label สำหรับแต่ละกลุ่มHandlerTuple(ndivide=None): แสดง Marker ทั้งหมดในกลุ่มเรียวติดกัน
ผลลัพธ์
Legend แสดง 2 รายการ: "y=sin(x)" มี Marker 2 แบบ (dashed, dashdot) และ "y=cos(x)" มี Marker 2 แบบ (solid, dotted)