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

การเพิ่ม Title ให้ Legend Rows ใน Matplotlib

สร้าง Legend ที่มี Header/Title สำหรับแต่ละกลุ่ม โดยสร้าง Empty Plot เป็น Placeholder

ขั้นตอน

  1. ตั้งค่าขนาด Figure
  2. สร้างข้อมูล Y และกำหนด Markers, Labels
  3. Plot หลายเส้นพร้อม Marker และ Label
  4. ดึง Handles และ Labels
  5. สร้าง Placeholder Handles สำหรับ Title
  6. รวมและแสดง Legend แบบหลายคอลัมน์

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


import matplotlib.pyplot as plt
import numpy as np

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

y = np.exp(-np.arange(5))
markers = ["s", "o", "*"]
labels = ["one", "two"]

fig, ax = plt.subplots()

for i in range(6):
    ax.plot(y * i + i / 2., marker=markers[i // 2], label=labels[i % 2])

h, l = ax.get_legend_handles_labels()

# สร้าง Placeholder สำหรับ Title (Empty plots)
ph = [plt.plot([], marker="", ls="")[0]] * 2
handles = ph + h
labels = ["Title 1:", "Title 2:"] + l

plt.legend(handles, labels, ncol=4)
plt.show()

วิธีที่ทันสมัยกว่า (Matplotlib 3.1+)


# ใช้ title parameter ใน legend
plt.legend(title="My Legend Title")

# หรือใช้ _legend_box (internal)
legend = ax.legend()
legend._legend_box.align = "left"

ผลลัพธ์

Legend แสดง 4 คอลัมน์: "Title 1:", "Title 2:" เป็น Header แล้วตามด้วย Marker และ Label ของแต่ละกลุ่ม