0

我有 20 个文件,我想绘制如下所示的文件,然后一个接一个地显示,类似于动画。一个给定的图看起来如图所示。在此处输入图像描述

这 20 个图的 y 轴范围不同。因此,虽然上图中显示的范围从 -184000 到 -176000,但另一个范围可能从 -160000 到 -170000。将轴保持在所有图形的最小值和最大值的范围内会导致图形过度拉伸或收缩。

我编写了以下代码:

import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig = plt.figure()
ims = []
for i in range(1, 21):
    file_out = "out" + "_" + str(i)
    outfile = pd.read_table(file_out, \
    skip_blank_lines=True, skipinitialspace=True, sep='\s+')
    x = outfile['col1']
    y = outfile['col2']
    im = plt.plot(x, y)
    ims.append(im)

ani = animation.ArtistAnimation(fig, ims, repeat=False, interval = 500)
plt.show()

有没有办法改变动画中每个新图形的轴范围?我尝试在代码中添加以下行,但没有成功: plt.axes(xlim = (0, 100), ylim = (min(y), max(y)))

谢谢!

4

1 回答 1

1

使用ArtistAnimation,所有线都绘制在相同的轴上,并在每帧切换可见/不可见,因此它们都处于相同的比例。为了得到想要的结果,我认为你需要使用FuncAnimation而不是ArtistAnimation.

像这样的东西(未经测试):

import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig = plt.figure()

def animate(i):
    file_out = "out" + "_" + str(i)
    outfile = pd.read_table(file_out,
                            skip_blank_lines=True, skipinitialspace=True, sep='\s+')
    x = outfile['col1']
    y = outfile['col2']
    plt.cla()
    im = plt.plot(x, y)
    return im

ani = animation.FuncAnimation(fig, animate, frames=range(1,21), repeat=False, interval = 500)
plt.show()
于 2020-11-18T22:05:53.203 回答