在Python中绘制for循环内部

时间:2017-11-12 02:59:15

标签: python animation matplotlib

我有一个代码,使用for循环解决一些时间相关的方程式,其中每次迭代都在时间上前进。我想在每次迭代结束时绘制到相同的图形但我不想在新图形存在后保留旧图形,我想看看图形如何变化 - 而不仅仅是跳到最后。这应该是一部关于结果如何变化的电影。它是这样的:

for k in range (0,100,1):

   #solve the equations

   #plot graph (x,y)

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

来自matplotlib examples

"""
=========================
Simple animation examples
=========================

This example contains two animations. The first is a random walk plot. The
second is an image animation.
"""

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


def update_line(num, data, line):
    line.set_data(data[..., :num])
    return line,

fig1 = plt.figure()

data = np.random.rand(2, 25)
l, = plt.plot([], [], 'r-')
plt.xlim(0, 1)
plt.ylim(0, 1)
plt.xlabel('x')
plt.title('test')
line_ani = animation.FuncAnimation(fig1, update_line, 25, fargs=(data, l),
                                   interval=50, blit=True)

# To save the animation, use the command: line_ani.save('lines.mp4')

fig2 = plt.figure()

x = np.arange(-9, 10)
y = np.arange(-9, 10).reshape(-1, 1)
base = np.hypot(x, y)
ims = []
for add in np.arange(15):
    ims.append((plt.pcolor(x, y, base + add, norm=plt.Normalize(0, 30)),))

im_ani = animation.ArtistAnimation(fig2, ims, interval=50, repeat_delay=3000,
                                   blit=True)
# To save this second animation with some metadata, use the following command:
# im_ani.save('im.mp4', metadata={'artist':'Guido'})

plt.show()