【问题标题】:Updating y axis ranges for each plot in matplotlib animation更新 matplotlib 动画中每个绘图的 y 轴范围
【发布时间】:2020-11-18 20:52:27
【问题描述】:

我有 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)))

谢谢!

【问题讨论】:

    标签: python matplotlib animation


    【解决方案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()
    

    【讨论】:

      猜你喜欢
      • 2016-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-17
      • 2014-07-10
      • 2018-12-11
      • 2014-02-27
      • 1970-01-01
      相关资源
      最近更新 更多