保留FuncAnimation帧之间的轴设置

时间:2016-12-17 21:29:24

标签: python animation matplotlib

我想生成一个来自不同文件的动画系列线图的视频。 下面是我的python代码的开始。 我正在使用matplotlib.animation 库。

看起来像这样:

three different line plots on top of each other

如何删除以前的图(一次显示一行), 但保持相同的轴和绘图尺寸?

如果我致电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")

2 个答案:

答案 0 :(得分:1)

仅更新动画中的数据而不是每次都创建新图表

可能是有意义的
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")

答案 1 :(得分:0)

plt.clf()中呼叫plot_initialize()plot_figure()

def plot_figure(filepath):
    print(filepath)
    columns = np.loadtxt(filepath, unpack=True)
    x = columns[0]
    y = columns[1]
    plt.clf()
    plot_initialize()
    plt.plot(x, y, color="blue", linewidth=1.0, linestyle="-")

结果:

enter image description here