我想从不同的文件中生成一系列折线图的动画视频。
以下是我的python代码的开始。
我正在使用matplotlib.animation
图书馆。
看起来像这样:
如何删除以前的绘图(一次显示一行),
但要保持相同的轴和图大小?
如果我叫plt.clf()
重置轴。
#! /usr/bin/env python
from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def plot_initialize():
plt.xlim(0, 6)
plt.ylim(0, 35)
plt.axis([0, 6, 0, 35])
def plot_figure(filepath):
print(filepath)
columns = np.loadtxt(filepath, unpack=True)
x = columns[0]
y = columns[1]
plt.plot(x, y, color="blue", linewidth=1.0, linestyle="-")
if __name__ == '__main__':
import tempfile
myfile1 = tempfile.NamedTemporaryFile()
myfile1.write('# myfile1\n1 2\n2 4\n3 6\n4 8\n5 10\n')
myfile1.seek(0)
myfile2 = tempfile.NamedTemporaryFile()
myfile2.write('# myfile2\n1 1\n2 4\n3 9\n4 16\n5 25\n')
myfile2.seek(0)
myfile3 = tempfile.NamedTemporaryFile()
myfile3.write('# myfile3\n1 2\n2 4\n3 8\n4 16\n5 32\n')
myfile3.seek(0)
filepaths = [myfile1.name, myfile2.name, myfile3.name]
my_figure = plt.figure()
anim = animation.FuncAnimation(my_figure, plot_figure, init_func=plot_initialize, frames=filepaths, interval=500, repeat=False)
anim.save("out.mp4")
最佳答案
仅更新动画中的数据而不是每次都创建新图可能是有意义的
from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def plot_initialize():
return
def plot_figure(filepath):
print(filepath)
columns = np.loadtxt(filepath, unpack=True)
x = columns[0]
y = columns[1]
line.set_data(x,y)
if __name__ == '__main__':
import tempfile
myfile1 = tempfile.NamedTemporaryFile()
myfile1.write('# myfile1\n1 2\n2 4\n3 6\n4 8\n5 10\n')
myfile1.seek(0)
myfile2 = tempfile.NamedTemporaryFile()
myfile2.write('# myfile2\n1 1\n2 4\n3 9\n4 16\n5 25\n')
myfile2.seek(0)
myfile3 = tempfile.NamedTemporaryFile()
myfile3.write('# myfile3\n1 2\n2 4\n3 8\n4 16\n5 32\n')
myfile3.seek(0)
filepaths = [myfile1.name, myfile2.name, myfile3.name]
my_figure = plt.figure()
plt.xlim(0, 6)
plt.ylim(0, 35)
plt.axis([0, 6, 0, 35])
line, = plt.plot([], [], color="blue", linewidth=1.0, linestyle="-")
anim = animation.FuncAnimation(my_figure, plot_figure, init_func=plot_initialize, frames=filepaths, interval=500, repeat=False)
anim.save("out.mp4")