Animate scatter points and line in matplotlib

Viewed 1099

I was trying to animate lines and scatter plot in matplotlib and coded the following Python script:-

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()

And the output generated is following:- enter image description here

But what I want is: that the yellow scatter point should appear in the plot after the red line has reached the location of the yellow point. My program is displaying the yellow point from the start, I want it to pop up at the end of the animation.

What can I add/update in the code to make the required changes?

1 Answers

I added simple condition to sc_2.

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

Code that I tested:

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()
Related