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

สร้าง Legend สำหรับเส้นแนวตั้งใน Matplotlib

ในการเพิ่ม Legend สำหรับเส้นแนวตั้ง (vertical line) ที่วาดด้วย ax.plot([x, x], [y1, y2]) ให้สร้าง proxy artist ด้วย matplotlib.lines.Line2D แล้วนำเข้า Legend

ขั้นตอน

  1. สร้าง Figure และ Axes
  2. วาดเส้นแนวตั้งด้วย ax.plot()
  3. สร้าง Line2D proxy artist ที่มี marker แบบแนวตั้ง
  4. เพิ่ม Legend ด้วย plt.legend(handles=[proxy])
  5. แสดงผล

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

import matplotlib.pyplot as plt
from matplotlib import lines

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

fig, ax = plt.subplots()
color = 'red'

# วาดเส้นแนวตั้งจริง
ax.plot([0, 0], [0, 3], color=color)

# สร้าง proxy artist สำหรับ legend
vertical_line = lines.Line2D(
    [], [], color=color, marker='|', linestyle='None',
    markersize=10, markeredgewidth=1.5, label='Vertical line'
)

plt.legend(handles=[vertical_line], loc='upper right')
plt.show()

ผลลัพธ์

จะแสดงกราฟมีเส้นแนวตั้งสีแดง และ Legend ด้านบนขวาแสดงสัญลักษณ์เส้นแนวตั้งพร้อมข้อความ "Vertical line"