ในการอัปเดตชื่อเนื้อเรื่องด้วย Matplotlib โดยใช้แอนิเมชั่น เราสามารถทำตามขั้นตอนต่อไปนี้ -
- กำหนดขนาดรูปและปรับช่องว่างภายในระหว่างและรอบๆ แผนผังย่อย
- สร้างตัวเลขใหม่หรือเปิดใช้งานตัวเลขที่มีอยู่โดยใช้ figure() วิธีการ
- สร้าง x และ ย จุดข้อมูลโดยใช้ตัวเลข
- รับแกนปัจจุบัน
- เพิ่มข้อความลงในแกนโดยใช้ text() วิธีการ
- เพิ่มวิธีการสร้างภาพเคลื่อนไหวที่ใช้สร้างภาพเคลื่อนไหวได้โดยการเรียกใช้ฟังก์ชันซ้ำๆ
- หากต้องการแสดงรูป ให้ใช้ show() วิธีการ
ตัวอย่าง
import numpy as np
from matplotlib import pyplot as plt, animation
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
fig = plt.figure()
x = np.linspace(-10, 10, 1000)
y = np.sin(x)
plt.plot(x, y)
ax = plt.gca()
ax.text(0.5, 1.100, "y=sin(x)", bbox={'facecolor': 'red',
'alpha': 0.5, 'pad': 5},
transform=ax.transAxes, ha="center")
def animate(frame):
ax.text(0.5, 1.100, "y=sin(x), frame: %d" % frame,
bbox={'facecolor': 'red', 'alpha': 0.5, 'pad': 5},
transform=ax.transAxes, ha="center")
ani = animation.FuncAnimation(fig, animate, interval=100,
frames=10, repeat=True)
plt.show() ผลลัพธ์
