การลบ Text Object ที่สร้างไว้ก่อนหน้า
เก็บ reference ของ text object ที่คืนจาก fig.text() แล้วเรียก .remove()
ขั้นตอนหลัก
- ตั้งค่าขนาดรูปและ padding
- สร้างข้อมูลและพล็อต
- สร้าง text ด้วย text = fig.text(0.5, 0.96, "$y=sin(x)$")
- ลบ text ด้วย text.remove() (uncomment เพื่อทดสอบ)
- แสดงผลด้วย show()
ตัวอย่างโค้ด
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
fig, ax = plt.subplots()
x = np.linspace(-10, 10, 100)
y = np.sin(x)
ax.plot(x, y)
text = fig.text(0.5, 0.96, "$y=sin(x)$")
# text.remove() # Uncomment to remove text
plt.show()
คำอธิบาย
fig.text() คืนค่า Text object เรียก .remove() ลบออกจาก figure artists list
วิธีอื่น
ใช้ ax.texts list สำหรับ text ที่เพิ่มผ่าน ax.text() แล้ววนลูป remove()