问题描述
我创建了一个脚本,该脚本为两个散布点和它们之间的一条线设置了动画。这是gif:
这是用于动画的脚本:
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,x_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()
我想要的是:当第一个散点出现时,将动画暂停2秒,然后对线进行动画处理;当线动画完成时,将动画再暂停2秒,然后显示散点。
我应该在代码中进行哪些更改以获得所需的动画?
解决方法
答案
您可以使用plt.pause()
来实现。
我简化了一些代码,以便在没有未知的a
模块(及其get_points()
函数)的情况下使用它。
代码
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()