เพื่อให้การจัดตำแหน่งข้อความในคำอธิบายแผนภูมิ matplotlib เราสามารถทำตามขั้นตอนต่อไปนี้ -
-
กำหนดขนาดรูปและปรับช่องว่างภายในระหว่างและรอบๆ แผนผังย่อย
-
สร้างจุดข้อมูล x โดยใช้ numpy
-
พล็อต x บาป(x) และ cos(x) โดยใช้ plot() วิธีการ
-
วางคำอธิบายโดยใช้ 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() ผลลัพธ์
