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

การสร้างอนิเมชันข้อความบนกราฟด้วย Matplotlib

การทำอนิเมชันข้อความใน Matplotlib ใช้คลาส FuncAnimation จากโมดูล matplotlib.animation โดยอัปเดตข้อความทีละตัวอักษรในแต่ละเฟรม

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

  1. ตั้งค่าขนาดรูปและขอบเขตแกน x, y
  2. สร้างข้อความเริ่มต้นด้วย ax.text()
  3. กำหนดฟังก์ชัน animate(i) เพื่ออัปเดตข้อความทีละตัว
  4. สร้างอนิเมชันด้วย FuncAnimation ระบุ frames และ interval
  5. ปิดแกนด้วย ax.axis('off') และแสดงผล

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

from matplotlib import pyplot as plt, animation

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

fig, ax = plt.subplots()
ax.set(xlim=(-1, 1), ylim=(-1, 1))

string = 'Hello, how are you doing?'
label = ax.text(0, 0, string[0], ha='center', va='center', fontsize=20, color="Red")

def animate(i):
    label.set_text(string[:i + 1])

anim = animation.FuncAnimation(fig, animate, interval=200, frames=len(string))
ax.axis('off')
plt.show()

ผลลัพธ์

การสร้างอนิเมชันข้อความบนกราฟด้วย Matplotlib