簡體   English   中英

嘗試在 Python 中制作 gif

[英]Trying to make a gif in Python

我正在用傅立葉級數逼近函數,我想以一種簡單的方式制作不同逼近的動畫 gif。 使用forplt.savefig命令,我為 gif 生成了不同的幀,但我無法為它們設置動畫。 這個想法是獲得這樣的東西圖片

這可以使用matplotlib.animation來完成。

編輯

我將向您展示如何繪制 x 的偶次冪,例如x^2x^4等。 看看下面的例子:

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

# Setting up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(-10, 10), ylim=(-10, 1000))
line, = ax.plot([], [], lw=2)

# initialization method: plot the background of each frame
def init():
    line.set_data([], [])
    return line,

# animation method.  This method will be called sequentially
pow_ = 2
def animate(i):
    global pow_
    x = np.linspace(-10, 10, 1000)
    y = x**pow_
    pow_+=2
    line.set_data(x, y)
    return line,

# call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=10, interval=200, blit=True)

# if you want to save this animation as an mp4 file, uncomment the line bellow
# anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])

plt.show()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM