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

เพิ่มรายการ Legend แบบ Manual ใน Matplotlib ด้วย Python


โดยใช้เมธอด plt.legend() เราสามารถสร้าง Legend ได้ และการส่งผ่าน frameon จะช่วยให้กรอบอยู่ที่นั่น

ขั้นตอน

  • ตั้งค่าป้ายกำกับแกน X ด้วย plt.xlabel()

  • ตั้งค่าป้ายกำกับแกน Y ด้วย plt.ylabel()

  • วาดเส้นด้วยเมธอด plot()

  • พารามิเตอร์ location และ legend_drawn_flag ช่วยหาตำแหน่งและทำให้แฟล็กเป็น True สำหรับกรอบ

  • ตั้งค่า legend ด้วยองค์ประกอบ "blue" และ "orange"

  • ใช้ plt.show() เพื่อแสดงกราฟ

ตัวอย่าง

import matplotlib.pyplot as plt
plt.ylabel("Y-axis ")
plt.xlabel("X-axis ")
plt.plot([9, 5], [2, 5], [4, 7, 8])
location = 0 # สำหรับตำแหน่งที่ดีที่สุด
legend_drawn_flag = True
plt.legend(["blue", "orange"], loc=0, frameon=legend_drawn_flag)
plt.show()

ผลลัพธ์

เพิ่มรายการ Legend แบบ Manual ใน Matplotlib ด้วย Python