试图在matplotlib动画上绘制仍然可见的图像

时间:2019-03-20 16:27:44

标签: python matplotlib animation

我有一个用Jupyter Notebook编写的代码制作的动画:

fig,ax=plt.subplots()
ax.set_xlim((0,512))
ax.set_ylim((0,512))

im=ax.imshow(data[0,:,:]) 
def init ():
    im.set_data(data[0,:,:])
    return(im,)
def animate(i):
    data_slice=data[i,:,:]
    im.set_data(data_slice)
    return(im,)


ani.FuncAnimation(fig,animate,init_func=init,frames=240,interval=100)

我无法弄清楚如何在其上绘制第一帧,同时使其半透明并保持动画在后台播放。我该如何实现?

谢谢。

1 个答案:

答案 0 :(得分:0)

您将必须创建两个图像,一个图像停留在顶部,另一幅图像被animate()修改:

# create dummy data
data = np.random.random(size=(240,512,512))
# load an image in first frame of data
temp = plt.imread('./stinkbug.png')
data[0,:,:] = 0.5
data[0,:375,:500] = temp[::-1,::-1,0]


fig,ax=plt.subplots()
ax.set_xlim((0,512))
ax.set_ylim((0,512))

top_img = ax.imshow(data[0,:,:], zorder=10, alpha=0.5, cmap='gray')
bottom_img = ax.imshow(data[1,:,:], zorder=1, cmap='viridis')

def init():
    top_img.set_data(data[0,:,:])
    bottom_img.set_data(data[1,:,:])
    return (top_img, bottom_img)
def animate(i):
    data_slice=data[i,:,:]
    bottom_img.set_data(data_slice)
    return (bottom_img,)


ani = animation.FuncAnimation(fig,animate,init_func=init,frames=range(1,240),interval=100)
plt.show()

enter image description here