Matplotlib暂停,保持最后一次迭代

时间:2016-11-01 12:09:58

标签: python matplotlib

我在matplotlib中有一个动画循环,我想冻结动画的最后一次迭代。我正在使用带有条件的pause函数来检查最后一次迭代。但是,在最后一次迭代中,显示的是前一帧 - 而不是最后一帧。

以下是一个例子:

import numpy as np
import matplotlib.pyplot as plt

fig,ax = plt.subplots(1,1)
x = np.linspace(0, 6.28, 401)

freqs = np.arange(5)

for f in freqs:
    print f

    ax.plot(x, np.sin(f*x))   
    ax.set_title('$\sin(%d x)$'%f)

    if f < freqs[-1]:
        plt.pause(1)
        ax.cla()
    else:
        print "hi"
        plt.show() # Fails: shows frame with `f==3`.

打印:

0
1
2
3
4
hi

但是,最后一帧(f==4)永远不会显示。动画冻结了标题,&#34; sin(3x)&#34;以及f==3的相应情节数据,而不是4。

是否有适当的&#34;保持最后一帧的方式?例如,plt.pause(10000)可以工作,但看起来像是黑客。

1 个答案:

答案 0 :(得分:1)

我总是发现首先设置绘图,绘制它然后开始动画更直观。

import numpy as np
import matplotlib.pyplot as plt

fig,ax = plt.subplots(1,1)
x = np.linspace(0, 6.28, 401)
freqs = np.arange(5)
line, = ax.plot([],[])
ax.set_xlim([x[0], x[-1]])   
ax.set_ylim([-1, 1])   
ax.set_title('$\sin(x)$')
fig.canvas.draw() 

for f in freqs:
    print f

    line.set_data(x, np.sin(f*x))   
    ax.set_title('$\sin(%d x)$'%f)
    fig.canvas.draw()

    if f < freqs[-1]:
        plt.pause(1)
    else:
        print "hi"
plt.show()