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

วิธีแสดง Legend แบบแนวนอนใน Matplotlib


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

  • กำหนดขนาดรูปภาพและปรับระยะห่างระหว่างและรอบๆ subplots
  • พล็อตเส้นด้วย plot() พร้อม label line1, line2, line3
  • วาง legend ด้วย legend() กำหนด ncol เท่ากับจำนวน label
  • ใช้เมธอด 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")
line3, = plt.plot([2, 3, 1], label="line3")
plt.legend(ncol=3, loc="upper right")
plt.show()

ผลลัพธ์

วิธีแสดง Legend แบบแนวนอนใน Matplotlib