如何在一个图中显示多个图像的变化?

时间:2014-05-23 09:06:07

标签: python numpy matplotlib

我的代码已根据本论坛中人们的许多好建议进行了修改。但是,我仍然对代码有一些疑问。 我的代码是:

from pylab import *
from numpy import *

N = 100 #lattice points per axis
dt = 1 #time step
dx = 1 #lattice spacing
t = arange(0, 1000000*dt, dt) #time
a = 1 #cofficient
epsilon = 100 #cofficient
M = 1.0 #cofficient
every = 100 #dump an image every

phi_0 = 0.5 #initial mean value of the order parameter
noise = 0.1 #initial amplitude of thermal fluctuations in the order parameter
th = phi_0*ones((N, N)) + noise*(rand(N, N) - 0.5) #initial condition

x, y = meshgrid(fftfreq(int(th.shape[0]), dx), fftfreq(int(th.shape[1]), dx))
k2 = (x*x + y*y) #k is a victor in the Fourier space, k2=x^2+y^2
g = lambda th, a: 4*a*th*(1-th)*(1-2*th) #function g

def update(th, dt, a, k2): 
    return ifft2((fft2(th)-dt*M*k2*fft2(g(th,a)))/(1+2*epsilon*M*dt*k2**2))

for i in range(size(t)):
    print t[i]
    if mod(i, every)==0:
            imshow(abs(th), vmin=0.0, vmax=1.0)
            colorbar()
            show()
            #savefig('t'+str(i/every).zfill(3)+'.png', dpi=100)
            clf()
    th=update(th, dt, a, k2)

当我运行它时,我必须逐个关闭数字以查看更改。但我想在一个图中展示图像的变化。有什么好主意吗?

1 个答案:

答案 0 :(得分:0)

使用matplotlib的“动画”功能,如

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)

plt.show()

教程: http://matplotlib.org/1.3.1/examples/animation/index.html