【发布时间】:2020-09-17 12:42:56
【问题描述】:
我创建了一个动画线和分散点的脚本,这里是脚本:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig, ax = plt.subplots(figsize=(16,8))
ax.set(xlim=(0,104), ylim=(0,68))
x_start, y_start = (50, 35)
x_end, y_end = (90, 45)
x = np.linspace(x_start, x_end, 20)
y = np.linspace(y_start, y_end, 20)
## the first scatter point
sc_1 = ax.scatter([], [], color="crimson", zorder=4, s=150, alpha=0.7, edgecolor="w")
## the line
line, = ax.plot([], [], color="black", zorder=4)
## the last scatter point
sc_2 = ax.scatter([], [], color="crimson", zorder=4, s=150, alpha=0.7, edgecolor="w")
## titles
title = ax.text(50, 65, "", bbox={'facecolor':'w', 'alpha':0.5, 'pad':5}, ha="center")
## scatter point which will follow the line
sc_3 = ax.scatter([], [], color="crimson", zorder=4, s=150, edgecolor="w")
def animate(i):
if i == 1:
sc_1.set_offsets([x_start, y_start])
title.set_text("Action 001")
if i == 2:
plt.pause(0.5)
title.set_text("Action 002")
## plot line
line.set_data(x[:i], y[:i])
## plot scatter point that will follow the line
sc_3.set_offsets(np.c_[x[:i], y[:i]])
## plot scatter point
if i > len(x):
plt.pause(0.2)
title.set_text("Action 003")
sc_2.set_offsets([x_end, y_end])
return sc_1, line, sc_2, title, sc_3
ani = animation.FuncAnimation(
fig=fig, func=animate, interval=50, blit=True)
ani.save("a.gif", writer="imagemagick")
plt.show()
它给出以下输出:
但是我想要的是在使用sc_3 为散点设置动画时,程序应该删除由sc_3 生成的散点的最后一次迭代,即散点不应该绘制在整条线上,只是一个散点会从头到尾跟随这条线。
最终的输出是这样的:行首的散点,然后一个散点将跟随该行(删除其最后的状态位置)和一个最终的散点在行的末尾
应该在程序中添加什么以获得所需的输出?
【问题讨论】:
标签: python matplotlib animation