ภาพรวม
ใช้โมดูล matplotlib.animation สร้างอนิเมชันข้อความที่เปลี่ยนขนาดและสีแบบเรียลไทม์
ขั้นตอนการทำงาน
- Import
animationจาก matplotlib - กำหนดขนาดฟิกเกอร์
- สร้าง figure และ axes
- เพิ่ม text object ด้วย
ax.text() - กำหนดรายการสีสำหรับสลับกัน
- สร้างฟังก์ชัน
animate()ที่อัปเดต fontsize และ color - ใช้
FuncAnimationเรียกฟังก์ชันซ้ำ - แสดงผล
ตัวอย่างโค้ด
from matplotlib import animation
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
fig = plt.figure()
ax = fig.add_subplot(111)
text = 'You are welcome!'
txt = ax.text(0.20, 0.5, text, fontsize=15)
colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd',
'#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']
def animate(num):
txt.set_fontsize(num * 2 + num)
txt.set_color(colors[num % len(colors)])
return txt,
anim = animation.FuncAnimation(fig, animate, frames=len(text) - 1, blit=True)
plt.show()
ผลลัพธ์
อนิเมชัน GIF แสดงข้อความขยายตัวและเปลี่ยนสี

การปรับแต่งเพิ่มเติม
- เปลี่ยน
framesเพื่อควบคุมจำนวนเฟรม - เพิ่ม
interval(ms) ใน FuncAnimation เพื่อควบคุมความเร็ว - ใช้
anim.save('text.gif', writer='pillow')บันทึกเป็นไฟล์ - สามารถอนิเมชัน position, rotation, alpha ได้เช่นกัน