python - 如何暂停 matplotlib 动画几秒钟(不使用任何鼠标点击)?

标签 python matplotlib animation pause

我创建了一个脚本,可以为两个散点和它们之间的一条线设置动画。这是动图:

这是用于动画的脚本:

from a import get_points
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time

fig, ax = plt.subplots(figsize=(12,8))
ax.set(xlim=(0,104), ylim=(0,68))

x_start, y_start = (50, 35)
x_end, y_end = (90, 45)

x_1, y_1 = get_points(x_start, y_start, x_end, y_end, 0.55)
x_2, y_2 = get_points(x_end, y_end, x_start, y_start, 0.55)

x = np.linspace(x_1, x_2, 20)
y = np.linspace(y_1, y_2, 20)

sc_1 = ax.scatter([], [], color="green", zorder=4)
line, = ax.plot([], [], color="crimson", zorder=4)
sc_2 = ax.scatter([], [], color="gold", zorder=4)
title = ax.text(50, 65, "", bbox={'facecolor':'w', 'alpha':0.5, 'pad':5}, ha="center")

def animate(i):
    ## plot scatter point
    sc_1.set_offsets([x_start, y_start])

    ## plot line
    line.set_data(x[:i], y[:i])

    ## plot scatter point
    if i == len(x):
        sc_2.set_offsets([x_end, y_end])

    return sc_1, line, sc_2, title,

ani = animation.FuncAnimation(  
    fig=fig, func=animate, interval=50, blit=True)  

plt.show()

我想要的是:当第一个散点出现时暂停动画 2 秒,然后为线设置动画,当线动画完成时暂停动画 2 秒,然后显示散点。

我应该在我的代码中更改什么以获得所需的动画?

最佳答案

回答

您可以使用 plt.pause() 来完成.
我稍微简化了您的代码,以便在没有未知的 a 模块(及其 get_points() 函数)的情况下使用它。

代码

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig, ax = plt.subplots(figsize=(12,8))
ax.set(xlim=(0,104), ylim=(0,68))

x_start, y_start = (50, 35)
x_end, y_end = (90, 45)

N = 20
x = np.linspace(x_start, x_end, N)
y = np.linspace(y_start, y_end, N)

sc_1 = ax.scatter([], [], color="green", zorder=4)
line, = ax.plot([], [], color="crimson", zorder=4)
sc_2 = ax.scatter([], [], color="gold", zorder=4)


def animate(i):
    sc_1.set_offsets([x_start, y_start])
    if i == 1:
        plt.pause(2)

    line.set_data(x[:i], y[:i])

    if i == len(x):
        plt.pause(2)
        sc_2.set_offsets([x_end, y_end])

    return sc_1, line, sc_2,

ani = animation.FuncAnimation(fig=fig, func=animate, interval=50, blit=True)

plt.show()

关于python - 如何暂停 matplotlib 动画几秒钟(不使用任何鼠标点击)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63922028/

相关文章:

python - 如何在 python 中创建优化的 3D 体积打包函数?

python - matplotlib - 运行时在事先不知道的情况下添加多行

flutter - 如何创建动画确定的圆形进度指示器?

ios - 当 Collection View 大小更改时,我需要帮助为 UICollectionView 单元格大小设置动画

animation - UITextfield 的 contentoffset 上的 UIView.animateWithDuration : It clips the text (Swift)

python - 您建议使用哪种 Python 方法来检查 whois 数据库记录?

python - Django - 使用 Gunicorn、Nginx 和 Supervisor 进行部署,Gunicorn 错误日志

python - 当我开始打字时 PyCharm 崩溃

python - Matplotlib NavigationToolbar 重叠图(在 PyQt4 嵌入中)

python - 导入 cv2 终端错误 - python