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

การจัดตำแหน่งข้อความใน Legend ของ Matplotlib


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

  • กำหนดขนาดรูปภาพและปรับระยะห่างระหว่างและรอบๆ subplots
  • สร้างข้อมูลจุด x ด้วย numpy
  • พล็อตกราฟ x, sin(x) และ cos(x) ด้วยเมธอด plot()
  • วางตำแหน่ง legend ด้วยเมธอด legend() และเริ่มต้นการตั้งค่า
  • วนลูปผ่านเมธอด legend.get_texts() เพื่อตั้งค่าการจัดตำแนวแนวนอน
  • ใช้เมธอด show() เพื่อแสดงรูปภาพ

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

import numpy as np
from matplotlib import pyplot as plt

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

x = np.linspace(-5, 5, 100)
plt.plot(x, np.sin(x), label="$y=sin(x)$")
plt.plot(x, np.cos(x), label="$y=cos(x)$")
legend = plt.legend(loc='upper right')
for t in legend.get_texts():
    t.set_ha('left')
plt.show()

ผลลัพธ์

การจัดตำแหน่งข้อความใน Legend ของ Matplotlib