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

วิธีใส่ Label ให้เส้นใน Matplotlib (Python)


ใช้ label ในอาร์กิวเมนต์ของ plot()

ขั้นตอนการทำงาน

  • กำหนดขนาดรูปภาพและปรับระยะห่างระหว่างและรอบๆ subplots
  • พล็อตพร้อม label="line1" ด้วย plot()
  • พล็อตพร้อม label="line2" ด้วย plot()
  • วาง legend ด้วย legend()
  • ใช้เมธอด show() เพื่อแสดงรูปภาพ

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

from matplotlib import pyplot as plt

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

line1, = plt.plot([1, 2, 3], label="line1")
line2, = plt.plot([3, 2, 1], label="line2")
leg = plt.legend(loc='upper center')
plt.show()

ผลลัพธ์

วิธีใส่ Label ให้เส้นใน Matplotlib (Python)