使用matplotlib保存散点图动画

2024-03-28 21:14:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直试图用matplotlib保存一个动画散点图,我希望它不需要完全不同的代码来作为动画人物查看和保存副本。此图完美地显示了保存完成后的所有数据点。

这段代码是Animating 3d scatterplot in matplotlib上的Giggi's的修改版本,其中修复了Yann's answerMatplotlib 3D scatter color lost after redraw的颜色(因为颜色在我的视频中很重要,所以我想确保它们正常工作)。

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
from mpl_toolkits.mplot3d import Axes3D

FLOOR = -10
CEILING = 10

class AnimatedScatter(object):
    def __init__(self, numpoints=5):
        self.numpoints = numpoints
        self.stream = self.data_stream()
        self.angle = 0

        self.fig = plt.figure()
        self.fig.canvas.mpl_connect('draw_event',self.forceUpdate)
        self.ax = self.fig.add_subplot(111,projection = '3d')
        self.ani = animation.FuncAnimation(self.fig, self.update, interval=100, 
                                       init_func=self.setup_plot, blit=True,frames=20)

    def change_angle(self):
        self.angle = (self.angle + 1)%360

    def forceUpdate(self, event):
        self.scat.changed()

    def setup_plot(self):
        X = next(self.stream)
        c = ['b', 'r', 'g', 'y', 'm']
        self.scat = self.ax.scatter(X[:,0], X[:,1], X[:,2] , c=c, s=200, animated=True)

        self.ax.set_xlim3d(FLOOR, CEILING)
        self.ax.set_ylim3d(FLOOR, CEILING)
        self.ax.set_zlim3d(FLOOR, CEILING)

        return self.scat,

    def data_stream(self):
        data = np.zeros(( self.numpoints , 3 ))
        xyz = data[:,:3]
        while True:
            xyz += 2 * (np.random.random(( self.numpoints,3)) - 0.5)
            yield data

    def update(self, i):
        data = next(self.stream)
        #data = np.transpose(data)

        self.scat._offsets3d = ( np.ma.ravel(data[:,0]) , np.ma.ravel(data[:,1]) , np.ma.ravel(data[:,2]) )

        plt.draw()
        return self.scat,

    def show(self):
        plt.show()

if __name__ == '__main__':
    a = AnimatedScatter()
    a.ani.save("movie.avi", codec='avi')
    a.show()

一个完全有效的.avi是由这个生成的,但是除了轴之外的所有四秒钟都是空白的。实际的数字总是准确地显示出我想看到的东西。如何像填充正常运行的动画一样填充save函数的绘图,或者在matplotlib中是否可能?

编辑:在更新中使用散点调用(不设置初始值设定项中的边界)会导致.avi显示轴增长,显示每次运行数据时,它只是没有显示在视频本身上。 我将matplotlib 1.1.1rc与Python 2.7.3一起使用。


Tags: importselfdatastreammatplotlibdefnpfig