I created a script that animates a line and scatters points, here is the script:
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()
It is giving the following output:
But what I want is while animating the scatter point using sc_3 the program should remove the last iteration of scatter point produced by sc_3, i.e. scatter point should not be plotted over the whole line, just a scatter point which will follow the line from start to the end.
The final output is like: scatter point at the start of the line and then a scatter point will follow the line(removing its last state position) and a final scatter point at the end of the line
What should be added in the program to get the desired output?

