简体   繁体   中英

Trying to make a gif in Python

I'm approximating functions with Fourier Series and I would like to make, hopefully in a simple way, an animated gif of the different approximations. With a for and plt.savefig commands I generate the different frames for the gif but I haven't been able to animate them. The idea is to obtain something like this图片

This can be done using matplotlib.animation .

EDIT

I'm going to show you how to plot even powers of x like x^2 , x^4 and so on. take a look at following example :

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM