I have created a script that animates two scatter points and a line in between them. Here is the gif:
And here is the script used for animation:
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()
What I want is: to pause the animation for 2 seconds when the first scatter point shows up then animate the line and when the line animation is complete pause animation for 2 more seconds and after that display the scatter point.
What should I change in my code to get the required animation?
You can do it with plt.pause()
.
I simplified a bit your code in order to use it without the unknown a
module (and its get_points()
function).
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()