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

การสร้างไฟล์ GIF แอนิเมชันจาก D3.js Animations ใน Matplotlib

ในการสร้างไฟล์ GIF แอนิเมชันจาก D3.js animation เราสามารถทำตามขั้นตอนต่อไปนี้:

  • ตั้งค่าขนาดรูปและปรับ padding ระหว่างและรอบ subplots
  • สร้าง figure ใหม่หรือเปิดใช้งาน figure ที่มีอยู่
  • เพิ่ม axes ให้กับ figure ปัจจุบันและทำให้เป็น axes ปัจจุบัน
  • พลอตเส้นด้วยลิสต์ว่าง
  • เพื่อเริ่มต้นเส้น ให้ส่งลิสต์ว่าง
  • เพื่อทำ animation เส้นไซน์ ให้อัปเดตค่าเส้นไซน์และคืนค่าอินสแตนซ์เส้น
  • รับอินสแตนซ์ movie writer โดยใช้คลาส PillowWriter()
  • บันทึกไฟล์ .gif โดยใช้ PillowWriter

ตัวอย่าง

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

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

fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)

def init():
    line.set_data([], [])
    return line,

def animate(i):
    x = np.linspace(0, 2, 1000)
    y = np.sin(2 * np.pi * (x - 0.01 * i))
    line.set_data(x, y)
    return line,

ani = animation.FuncAnimation(fig, animate, init_func=init, frames=200, interval=20, blit=True)
writer = animation.PillowWriter(fps=25)
ani.save("sine.gif", writer=writer)

ผลลัพธ์

การสร้างไฟล์ GIF แอนิเมชันจาก D3.js Animations ใน Matplotlibการสร้างไฟล์ GIF แอนิเมชันจาก D3.js Animations ใน Matplotlib