暫停和恢復動畫#

此範例展示了

  • 使用 Animation.pause() 方法暫停動畫。

  • 使用 Animation.resume() 方法恢復動畫。

注意

此範例會執行 Matplotlib 的互動功能,且不會顯示在靜態文件中。請在您的機器上執行此程式碼,以查看互動性。

您可以複製並貼上個別部分,或使用頁面底部的連結下載整個範例。

透過 matplotlib.animation.Animation.to_jshtml 產生的輸出。

Click to pause/resume the animation
import matplotlib.pyplot as plt
import numpy as np

import matplotlib.animation as animation


class PauseAnimation:
    def __init__(self):
        fig, ax = plt.subplots()
        ax.set_title('Click to pause/resume the animation')
        x = np.linspace(-0.1, 0.1, 1000)

        # Start with a normal distribution
        self.n0 = (1.0 / ((4 * np.pi * 2e-4 * 0.1) ** 0.5)
                   * np.exp(-x ** 2 / (4 * 2e-4 * 0.1)))
        self.p, = ax.plot(x, self.n0)

        self.animation = animation.FuncAnimation(
            fig, self.update, frames=200, interval=50, blit=True)
        self.paused = False

        fig.canvas.mpl_connect('button_press_event', self.toggle_pause)

    def toggle_pause(self, *args, **kwargs):
        if self.paused:
            self.animation.resume()
        else:
            self.animation.pause()
        self.paused = not self.paused

    def update(self, i):
        self.n0 += i / 100 % 5
        self.p.set_ydata(self.n0 % 20)
        return (self.p,)


pa = PauseAnimation()
plt.show()

Sphinx-Gallery 產生的圖庫