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

วิธีวาด Inline Line Labels ใน Matplotlib

การแสดง Label ตรงบนเส้นกราฟ (Inline Labels)

ใช้ไลบรารี labellines และฟังก์ชัน labelLines()

ขั้นตอนหลัก

  • ตั้งค่าขนาดรูปและ padding
  • สร้างข้อมูล X และพารามิเตอร์ A
  • วนลูปพล็อตแต่ละเส้นพร้อม label
  • เรียก labelLines(plt.gca().get_lines(), zorder=2.5)
  • แสดงผลด้วย show()

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

import numpy as np
from matplotlib import pyplot as plt
from labellines import labelLines

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

X = np.linspace(0, 1, 500)
A = [1, 2, 5, 10, 20]

for a in A:
    plt.plot(X, np.arctan(a*X), label=str(a))

labelLines(plt.gca().get_lines(), zorder=2.5)
plt.show()

ข้อกำหนด

ติดตั้ง labellines: pip install labellines

คำอธิบาย

labelLines() วาง label ตรงบนเส้นกราฟโดยอัตโนมัติ หลีกเลี่ยงการทับซ้อน