alg*_*gol 3 python animation matplotlib
我一直在使用 matplotlib 为一些图像制作动画,但我现在发现我想为这些动画添加更多信息,所以我想覆盖一个指示重要特征的散点图。这是迄今为止我一直用于生成电影的代码:
def make_animation(frames,path,name): 
    plt.rcParams['animation.ffmpeg_path'] = u'/Users/~/anaconda3/bin/ffmpeg' #ffmpeg path    
    n_images=frames.shape[2] 
    assert (n_images>1)   
    figsize=(10,10)
    fig, ax = plt.subplots(figsize=figsize)
    fig.tight_layout()
    fig.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=None, hspace=None)
    #lineR, = ax.plot(xaxis_data[0],R_data[0],'c-',label="resources")
    img = ax.imshow(frames[:,:,0], animated = True)   
    def updatefig(img_num): 
        #lineR.set_data(xaxis_data[img_num],R_data[img_num],'r-')
        img.set_data(frames[:,:,img_num])
        return [img]
    ani = animation.FuncAnimation(fig, updatefig, np.arange(1, n_images), interval=50, blit=True)
    mywriter = animation.FFMpegWriter(fps = 20)
    #ani.save('mymovie.mp4',writer=mywriter)
    ani.save("/Users/~/output/"+ path + "/" + name + ".mp4",writer=mywriter)
    plt.close(fig)
我想在每一帧的顶部添加一个散点图,就像我可以用这样的常规图做的那样:
fig, ax = plt.subplots()
img = ax.imshow(frames[:,:,0])
img = ax.scatter(scatter_pts[0],scatter_pts[1],marker='+',c='r')
我在这方面的第一次尝试看起来像这样:
def make_animation_scatter(frames,path,name,scatter): 
    plt.rcParams['animation.ffmpeg_path'] = u'/Users/~/anaconda3/bin/ffmpeg' #ffmpeg path    
    n_images=frames.shape[2] 
    assert (n_images>1)   
    figsize=(10,10)
    fig, ax = plt.subplots(figsize=figsize)
    fig.tight_layout()
    fig.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=None, hspace=None)
    #lineR, = ax.plot(xaxis_data[0],R_data[0],'c-',label="resources")
    img = ax.imshow(frames[:,:,0], animated = True)   
    img = ax.scatter(scatter[0],scatter[1],c='r',marker = '+')
    def updatefig(img_num): 
        #lineR.set_data(xaxis_data[img_num],R_data[img_num],'r-')
        img.set_data(frames[:,:,img_num])
        img = ax.scatter(scatter[0],scatter[1],c='r',marker = '+')
        return [img]
    ani = animation.FuncAnimation(fig, updatefig, np.arange(1, n_images), interval=50, blit=True)
    mywriter = animation.FFMpegWriter(fps = 20)
    #ani.save('mymovie.mp4',writer=mywriter)
    ani.save("/Users/~/output/"+ path + "/" + name + ".mp4",writer=mywriter)
    plt.close(fig)
这会产生一个没有散点图的视频,所以我想知道如何正确实现它。
小智 5
该文件说,当blit=True使用您必须从更新功能,以重绘它们返回一个“可迭代的艺术家”。但是,您只是返回img. 此外,您正在img使用图像和分散对象进行覆盖。你想要的是为散点使用不同的名称,例如
img = ax.imshow(frames[:,:,0], animated = True)
sct = ax.scatter(scatter[0],scatter[1],c='r',marker = '+')
两者仍将绘制在同一轴上,但现在您拥有img和sct艺术家,然后更新功能将是
def updatefig(img_num, img, sct, ax):
    img.set_data(frames[:,:,img_num])
    sct = ax.scatter(scatter[0], scatter[1], c='r', marker='+')
    return [img, sct]