一维动画

时间:2017-11-04 11:38:15

标签: python animation

我有425个文件,Ex1,Ex2,Ex3,...,Ex425。每个文件对应一个时间步。每个文件包含一列电场幅度。所以在时间t = 1时,Ex1是空间中200个点的场,依此类推。我想在python中制作这些文件的一维动画,但无法实现。有人可以帮忙吗?

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

basename = "Ex"
numFiles = 425

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

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

def animate(i):
    x = np.linspace(0, 200, 1)
    for t in range(1,numFiles):
        filename = basename + str(t) 
        data = np.loadtxt(filename)
    line.set_data(x, data[:,0])
    return line,

anim = animation.FuncAnimation(fig, animate, 
init_func=init,frames=200, interval=20, blit=True)

plt.show()

1 个答案:

答案 0 :(得分:0)

好的,首先让我们以我认为属于你的格式生成一些文件:

for i in range(11):
    a = open("test%i.txt"%i, "w")
    for j in np.random.rand(200)*i%5:
        a.write(str(j)+"\n")
    a.close()

这是一种动态绘制内容的方法:

## this function reads your files
# returns a list of strings
def read_files(filename):
    myfile = open(filename)
    file_content= myfile.readlines()
    myfile.close()
    return file_content

x = np.linspace(1, 200, 200)
y = np.ones(200) * np.nan

plt.ion() # enables figure updating

fig = plt.figure()
ax = fig.add_subplot(111)

## configure the plot
## these initial values for x and y will never be shown
line1, = ax.plot(x, y, 'b')  #     

## Loops through your files
for File in glob.glob("test*.txt"):
    y = read_files(File)
    line1.set_ydata(y)

    # recompute the ax.dataLim
    ax.relim()
    # update ax.viewLim using the new dataLim
    ax.autoscale_view()
    fig.canvas.draw() # display/update

    time.sleep(2)

有关动态扩展的详细信息,请查看this answer