python - 在 matplotlib 中动画散点和线

标签 python matplotlib

我试图在 matplotlib 中制作线条和散点图的动画,并编写了以下 Python 脚本:-

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

pitch = Pitch(line_color='grey', pitch_color='#121212', orientation='horizontal')
fig, ax = pitch.create_pitch() 

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, 50)
y = np.linspace(y_1, y_2, 50)

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):
    ## plot scatter point
    sc_1.set_offsets([x_start, y_start])

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

    ## plot scatter point
    sc_2.set_offsets([x_end, y_end])

    return sc_1, line, sc_2

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

plt.show()

生成的输出如下:- enter image description here

但我想要的是:在红线到达黄点的位置后,黄色散点应该出现在图中。我的程序从一开始就显示黄色点,我希望它在动画结束时弹出。

我可以在代码中添加/更新什么以进行所需的更改?

最佳答案

我向 sc_2 添加了简单的条件。

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

我测试的代码:

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


fig, ax = plt.subplots()

x_start, y_start = (0, 0)
x_end, y_end = (90, 90)

x_1, y_1 = 0, 0
x_2, y_2 = 90, 90

plt.xlim((0, 100))
plt.ylim((0,100))

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

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):
    ## 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

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

plt.show()

关于python - 在 matplotlib 中动画散点和线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63919284/

相关文章:

python - 有更好的方法来清理字典吗?

python - matplotlib 图例位置默认

python - 删除 x 刻度但保留网格线

python - 有没有办法在 Matplotlib 中从不接触的两个垂直函数之间进行着色?

python - Emacs:名为 "virtualenv"的程序不存在

python - SSL:CERTIFICATE_VERIFY_FAILED 证书验证失败 (_ssl.c.661)

python - 如何使用给定范围删除重复项并强制 numpy 数组中的元素是唯一的?

Python:名称评估如何在运行时执行

matplotlib - 更改 Matplotlib 中科学计数法刻度标签的大小

python - 在 matplotlib 中将 lat/lon 转换为 x/y 以进行 imshow