gpt4 book ai didi

python - 保留 FuncAnimation 帧之间的轴设置

转载 作者:太空宇宙 更新时间:2023-11-03 15:51:51 26 4
gpt4 key购买 nike

我想从不同的文件生成一系列动画线图的视频。下面是我的 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")

最佳答案

仅更新动画中的数据而不是每次都创建新的绘图可能是有意义的

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")

关于python - 保留 FuncAnimation 帧之间的轴设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41203258/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com