• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python animation.FuncAnimation类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中matplotlib.animation.FuncAnimation的典型用法代码示例。如果您正苦于以下问题:Python FuncAnimation类的具体用法?Python FuncAnimation怎么用?Python FuncAnimation使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了FuncAnimation类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: AnimationWidget

class AnimationWidget(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)

        vbox = QtGui.QVBoxLayout()
        self.canvas = MyMplCanvas(self, width=5, height=4, dpi=100)
        vbox.addWidget(self.canvas)

        hbox = QtGui.QHBoxLayout()
        self.start_button = QtGui.QPushButton("start", self)
        self.stop_button = QtGui.QPushButton("stop", self)
        self.start_button.clicked.connect(self.on_start)
        self.stop_button.clicked.connect(self.on_stop)
        hbox.addWidget(self.start_button)
        hbox.addWidget(self.stop_button)
        vbox.addLayout(hbox)
        self.setLayout(vbox)

        self.x = np.linspace(0, 5*np.pi, 400)
        self.p = 0.0
        self.y = np.sin(self.x + self.p)
        self.line, = self.canvas.axes.plot(self.x, self.y, animated=True, lw=2)

    def update_line(self, i):
        self.p += 0.1
        y = np.sin(self.x + self.p)
        self.line.set_ydata(y)
        return [self.line]

    def on_start(self):
        self.ani = FuncAnimation(self.canvas.figure, self.update_line,
                                 blit=True, interval=25)

    def on_stop(self):
        self.ani._stop()
开发者ID:shuxue051,项目名称:DataMaster,代码行数:35,代码来源:pyqt_demo.py


示例2: record_gif

	def record_gif(self, gen_func, savefn):
		gen = gen_func()
		frame_func = lambda t: next(gen)
		ax = plt.subplot(1,1,1)
		f = ax.get_figure()
		animation = FuncAnimation(f, frame_func, frames = np.arange(0,10,0.1), interval = 200)
		animation.save(savefn + '.gif', dpi = 80, writer = 'imagemagick')
开发者ID:AmmarKothari,项目名称:ROB541_GeometricMecahnics,代码行数:7,代码来源:HW3.py


示例3: __init__

    def __init__(self, fig, startFrame, endFrame, tail, fade=False, **kwargs) :
        """
        Create an animation of track segments.

        *fig*               matplotlib Figure object
        *startFrame*        The frame number to start animation loop at
        *endFrame*          The frame number to end the loop at
        *tail*              How many frames to keep older segments in view
        *fade*              Whether or not to fade track tails for
                            non-active tracks (default: False).

        All other :class:`FuncAnimation` constructor  kwargs are available
        except *frames* and *fargs*.

        TODO: Add usage info.
        """
        self._lineData = []
        self._lines = []
        if 'frames' in kwargs :
            raise KeyError("Do not specify 'frames' for the constructor"
                           " of SegAnimator")

        self.fade = fade

        FuncAnimation.__init__(self, fig, self.update_lines,
                                     endFrame - startFrame + 1,
                                     fargs=(self._lineData, self._lines,
                                            startFrame, endFrame, tail),
                                     **kwargs)
开发者ID:BVRoot,项目名称:ZigZag,代码行数:29,代码来源:TrackPlot.py


示例4: main

def main():
	fig = plt.figure(figsize=(3.2, 1.8))
	ax = fig.add_axes([0, 0, 1, 1])

	signal = create_gammapy_skymap().data
	background = np.ones(signal.shape)
	background /= background.sum()

	data = (1 * signal + background) / 2.

	# setup counts generator
	pdf = data.copy().flatten()
	x = np.arange(pdf.size)
	counts_generator = rv_discrete(name='counts', values=(x, pdf))

	counts = np.zeros_like(data)

	image = ax.imshow(counts, cmap='afmhot', origin='lower', vmin=0, vmax=9,
					  interpolation='None')
	bins = np.arange(counts.size + 1) - 0.5

	anim = FuncAnimation(fig, animate, fargs=[image, counts, bins, counts_generator],
                         frames=200, interval=50)
	
	filename = 'gammapy_logo.gif'
	anim.save(filename, writer='imagemagick')
开发者ID:OlgaVorokh,项目名称:gammapy-extra,代码行数:26,代码来源:gammapy_poisson_logo.py


示例5: Blocks

class Blocks():
    def __init__(self, numBlocks,L,data, point_count,colormap): 
        self.point_count     = point_count
        self.data           = data
        self.c              = data-data[0]
        self.positions      = np.linspace(0,L,numBlocks)
        self.get_color_range(colormap, self.c)

        self.fig,self.ax    = plt.subplots()
        self.scatter        = plt.scatter(self.data[0],np.zeros_like(self.data[0]), 
                                                c=self.crange[0],s=50, 
                                                cmap = colormap)

        self.animation      = FuncAnimation(self.fig, self.update,data.shape[0], 
                                                fargs=(self.data, self.scatter), 
                                                interval =25)

    def get_color_range(self,colormap, c):
        mapper = cm.ScalarMappable(cmap = colormap)
        self.crange = mapper.to_rgba(c)


    def update(self,num,data, scat):
        array           = np.array((data[num],np.zeros_like(data[num]))).T
        
        self.scatter.set_offsets(array)
        self.scatter.set_facecolor(self.crange[num]), 
        print ("%d/%d" %(num,self.point_count))
        return self.scatter,

    def animate(self, numBlocks, save = False, filename="output/animation.gif"):
        plt.show()
        if save:
            print("Writing to %s, this make take a while" %filename)
            self.animation.save(filename, writer='imagemagick', fps=30)
开发者ID:halvarsu,项目名称:uio-grand-challenge,代码行数:35,代码来源:animate.py


示例6: plot_worker

def plot_worker(queue, animation=False):
    """Matplotlib worker."""

    def init():
        updated_lines = []
        for ax_lines in lines:
            for line, x, y in ax_lines:
                line.set_data([], [])
                updated_lines.append(line)
        return updated_lines

    fig, axes, lines = make_subplots()
    # Important to assign it to a variable, even if we don't use it.
    anim = FuncAnimation(fig=fig,
                         func=update_figure,
                         frames=lambda: get_data(queue),
                         fargs=(lines, axes),
                         interval=200,
                         repeat=False,
                         init_func=init,
                         blit=False)
    if animation:
        anim.save('plot.mp4', fps=10, extra_args=['-vcodec', 'libx264'])
    else:
        plt.show()
开发者ID:bwbaugh,项目名称:infertweet,代码行数:25,代码来源:plot.py


示例7: showAnimation

	def showAnimation(self, Nframe=500):
		ax = self.fig.add_axes([0,0,1,1])
		plt.cla()
		color_map = {1:'b', 2:'r', 3:'g'}
				
		animation = FuncAnimation(self.fig, self.updateFig, interval=50, blit=False, frames=Nframe)
		animation.save("LanguageAdoptionModel.mp4")
开发者ID:chocolates,项目名称:ABM-course-project,代码行数:7,代码来源:language_adoption2.py


示例8: run

 def run(self, animating = False, iteration_count = 10000):
     
     population_counts = np.zeros((2, iteration_count), dtype=int)
     
     def loop(t):
         if animating:
             self.draw()
         self.step()
         for agent in self.agents:
             if agent.type == PREDATOR:
                 population_counts[0,t] += 1
             else:
                 population_counts[1,t] += 1
     
     if animating:
         figure = plt.figure()
         figure.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=None, hspace=None)
         animation = FuncAnimation(figure, loop, init_func=self.init_drawing,
                                   frames=iteration_count)
         # save video
         directory = "videos"
         if not os.path.exists(directory):
             os.makedirs(directory)
         filename = "{}/{}.mp4".format(directory, datetime.now())
         animation.save(filename, fps=20, codec="libx264", extra_args=['-pix_fmt','yuv420p'])
     else:
         animation = None
         for t in range(iteration_count):
             loop(t)
             if np.any(population_counts[:,t] == 0):
                 return population_counts[:, :t + 1]
     
     return population_counts
开发者ID:sebhoerl,项目名称:SOCS,代码行数:33,代码来源:predator_prey.py


示例9: main

    def main(self, outfile, fps=30):

        frame = defaultdict(list)
        for _, [t, item], val in self.interp.chart['frame/2'][:,:,:]:
            if val:
                frame[t].append(item)

        nframes = max(frame)

        def draw_frame(t):
            ax.cla()
            ax.set_title(t)
            ax.set_xlim(-2,2)   # TODO: this isn't right...
            ax.set_ylim(-2,2)
            if t not in frame:
                print 'frame', t, 'missing.'
            for item in frame[t]:
                if item.fn == 'line/2':
                    [(a,b), (c,d)] = map(topython, item.args)
                    ax.plot([a,c], [b,d], color='b', alpha=0.5)
                elif item.fn == 'text/2':
                    (s,(x,y)) = map(topython, item.args)
                    ax.text(x,y,s)
                else:
                    print 'dont know how to render', item

        fig = pl.figure()
        ax = pl.axes()
        anim = FuncAnimation(fig, draw_frame, frames=nframes)
        anim.save(outfile, fps=fps, extra_args=['-vcodec', 'libx264'])
开发者ID:jeisner,项目名称:dyna,代码行数:30,代码来源:graph.py


示例10: plot_data_scatterplot

def plot_data_scatterplot(x, y, mb_history=None):
    """Plot the data: y as a function of x, in a scatterplot.

    x, y: arrays of data.
    mb_history:
        if provided, it's a sequence of (m, b) pairs that are used to draw
        animated lines on top of the scatterplot.
    """
    fig, ax = plt.subplots()
    fig.set_tight_layout(True)
    fig.set_size_inches((8, 6))
    save_dpi = 80

    ax.scatter(x, y, marker='x')
    ax.set_xlabel('x')
    ax.set_ylabel('y')

    if mb_history:
        m0, b0 = mb_history[0]
        line, = ax.plot(x, x * m0 + b0, 'r-', linewidth=2.0)

        # Downsample mb_history by 2 to reduce the number of frames shown.
        def update(frame_i):
            mi, bi = mb_history[frame_i * 2]
            line.set_ydata(x * mi + bi)
            ax.set_title('Fit at iteration {0}'.format(frame_i * 2))
            return [line]

        anim = FuncAnimation(fig, update, frames=range(len(mb_history) // 2),
                             interval=200)
        anim.save('regressionfit.gif', dpi=save_dpi, writer='imagemagick')
    else:
        fig.savefig('linreg-data.png', dpi=save_dpi)
    plt.show()
开发者ID:rehlotus,项目名称:assignments,代码行数:34,代码来源:simple_linear_regression.py


示例11: confusion_worker

def confusion_worker(queue, animation=False):
    """Matplotlib worker."""

    config = get_config()
    titles = json.loads(config.get('sentiment', 'titles'))

    def init():
        clear_annotations(annotations)
        for ax, image, title in zip(axes, images, titles):
            empty_confusion = [[0] * 3] * 3
            image.set_data(empty_confusion)
            # annotate_confusion_matrix(ax, empty_confusion, annotations)
        return images

    fig, axes, images, annotations = make_confusion()
    # Important to assign it to a variable, even if we don't use it.
    anim = FuncAnimation(fig=fig,
                         func=update_confusion,
                         frames=lambda: get_data(queue),
                         fargs=(images, axes, annotations),
                         interval=200,
                         repeat=False,
                         init_func=init,
                         blit=False)
    if animation:
        anim.save('confusion.mp4', fps=10, extra_args=['-vcodec', 'libx264'])
    else:
        plt.show()
开发者ID:bwbaugh,项目名称:infertweet,代码行数:28,代码来源:plot.py


示例12: generate

 def generate(self, run_data):
     self._print_generating_line()
     self.fig = plt.figure()
     self.initial(run_data)
     anim = FuncAnimation(self._fig, self.animate, frames=len(self._times),
         interval=run_data.log_interval_ticks)
     anim.save(self.get_figfilename(), dpi=self.dpi)
     plt.close(self.fig)
开发者ID:XianliangJ,项目名称:remy,代码行数:8,代码来源:plot_log.py


示例13: animate

def animate(basetimer,fig,timer=None,save=None,**ka):
  ka['repeat'] = ka['repeat_delay']>0
  from matplotlib.animation import FuncAnimation
  anim = FuncAnimation(fig,save_count=1,**ka)
  if timer is not None:
    config(basetimer,**timer)
    basetimer.launch(anim)
  if save is not None: anim.save(**save)
开发者ID:jmandreoli,项目名称:PYTOOLS,代码行数:8,代码来源:animate.py


示例14: main

def main(data,outmov):
    #entropy calculation with plots
    fun = lik.VESPA_fit(data,spec_lib='bc03')
    
    SSP = fun.SSP
    ages = fun._age_unq
    metal = nu.linspace(fun._metal_unq.min(),fun._metal_unq.max(),10)

    t,z = nu.meshgrid(ages,metal)
    spec = []
    d = nu.vstack((t.ravel(),z.ravel())).T
    for i in d:
        try:
            spec.append(SSP.get_sed(10**(i[0]-9),10**i[1]))
        except:
            spec.append(SSP.get_sed(round(10**(i[0]-9)),10**i[1]))

    #make array
    spec = nu.asarray(spec)
    #match wavelenth with data
    if not nu.all(nu.sort(SSP.sed_ls) == SSP.sed_ls):
        #check if sorted
        wave = SSP.sed_ls[::-1]
        spec = spec[:,::-1]
    else:
        wave = SSP.sed_ls
    new_spec = nu.zeros((len(d),len(data)))
    for i in xrange(len(d)):
        new_spec[i,:] = nu.interp(data[:,0],wave,spec[i,:])
    spec = new_spec
    H = get_information(data,spec)
    
    #make animation of how information changes likelihood
    #get spectra
    chi = []
    flux = data[:,1]
    #how i think the enropy should look -sum((1-p)*log(p))
    #tot_infor = nu.sum(mod_shannon(H))
    #H = mod_shannon(H)
    H = shannon(H)
    wave =data[:,0]
    del_index = flux == flux
    print 'Making images'
    for i in xrange(len(wave)):
        index = nu.nanargmin(H)
        H[index] = nu.nan
        del_index[index] = False
        chi.append([make_chi(flux[del_index],spec,t,z,del_index),nu.nansum(H),nu.copy(del_index)])
    pik.dump((chi,z,t,wave,flux),open('temp.pik','w'),2)
    print 'Saving animations as movie'
    #make animation
    an = anim(t, z, chi, wave, flux)
    ani = FuncAnimation(an.fig,an.make_im,frames = len(chi))
    ani.save(outmov+'.mp4')
开发者ID:drdangersimon,项目名称:ageDate,代码行数:54,代码来源:tests.py


示例15: __init__

    def __init__(self, fig, files, load_func=None, robust=False, **kwargs):
        """
        Create an animation object for viewing radar reflectivities.

        *fig*           matplotlib Figure object

        *files*         list of filenames containing the radar data

        *load_func*     The function to use to load the data from a file.
                        Must return a dictionary of 'vals' which contains
                        the 3D numpy array (T by Y by X), 'lats' and 'lons'.

                        It is also optional that the loading function also
                        provides a 'scan_time', either as a
                        :class:`datetime.datetime` object or as an integer
                        or a float representing the number of seconds since
                        UNIX Epoch.

        *frames*        The number of frames to display. If not given, then
                        assume it is the same number as 'len(files)'.

        *robust*        Boolean (default: False) indicating whether or not
                        we can assume all the data will be for the same domain.
                        If you can't assume a consistant domain, then set
                        *robust* to True.  This often happens for PAR data.
                        Note that a robust rendering is slower.

        All other kwargs for :class:`FuncAnimation` are also allowed.

        To use, specify the axes to display the image on using :meth:`add_axes`.
        """
        self._rd = files
        self._loadfunc = load_func if load_func is not None else LoadRastRadar

        self._ims = []
        self._im_kwargs = []
        self._new_axes = []
        self._curr_time = None
        self._robust = robust
        frames = kwargs.pop("frames", None)
        # if len(files) < frames :
        #    raise ValueError("Not enough data files for the number of frames")
        FuncAnimation.__init__(
            self,
            fig,
            self.nextframe,
            frames=len(self._rd),
            #                                     init_func=self.firstframe,
            **kwargs
        )
开发者ID:BVRoot,项目名称:BRadar,代码行数:50,代码来源:plotutils.py


示例16: __init__

    def __init__(self, fig, grid, filelists,
                       load_funcs=None, robusts=False, **kwargs) :

        self._filelists = [cycle(files) for files in filelists]
        self._loadfunc = load_func if load_func is not None else LoadRastRadar
        self._curr_times = [None] * len(filelists)
        self._ims = [None] * len(filelists)
        self._datas = [None] * len(filelists)
        #self.im_kwargs = [None] * len(filelists)
        self._has_looped = [False] * len(filelists)
        self._grid = grid
        self.robust = robust

        FuncAnimation.__init__(self, fig, self.nexttick, blit=False,
                                          init_func=self.firsttick, **kwargs)
开发者ID:WeatherGod,项目名称:BRadar,代码行数:15,代码来源:radarmovie.py


示例17: __init__

 def __init__(self, fig, func, frames=None, init_func=None, fargs=None,
              save_count=None, mini=0, maxi=100, pos=(0.2, 0.98), **kwargs):
     self.i = 0
     self.min = mini
     self.max = maxi
     self.runs = True
     self.forwards = True
     self.fig = fig
     self.func = func
     self.setup(pos)
     FuncAnimation.__init__(
         self, self.fig, self.update, frames=self.play(),
         init_func=init_func, fargs=fargs,
         save_count=save_count, **kwargs
     )
开发者ID:chemreac,项目名称:chemreac,代码行数:15,代码来源:_player.py


示例18: anim

def anim():
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')

    ax.set_xlim3d([-20.0, 20.0])
    ax.set_xlabel('X')
    ax.set_ylim3d([-20.0, 20.0])
    ax.set_ylabel('Y')
    ax.set_zlim3d([-20.0, 20.0])
    ax.set_zlabel('Z')
    ax.set_title('3D Test')

    sc = [ax.scatter(points[0][i][0], points[0][i][1], points[0][i][2], c='b', s=0.1,facecolor='0.5', lw = 0) for i in range(len(points[0]))]
    ani = FuncAnimation(fig, update, frames=3000,
                        fargs=(points, sc, ax), interval=10)
    ani.save("basic_animation.mp4", fps=30, extra_args=['-vcodec', 'libx264'])
开发者ID:richard-liang,项目名称:DataAnim,代码行数:16,代码来源:data.py


示例19: animate

def animate(data, arrowscale=1, savepath=None):
    """ animates the quiver plot for the dataset (multiple frames) 
    Input:
        data : xarray PIV type of DataSet
        arrowscale : [optional] integer, default is 1
        savepath : [optional] path to save the MP4 animation, default is None
    
    Output:
        if savepath is None, then only an image display of the animation
        if savepath is an existing path, a file named im.mp4 is saved
    
    """    
    X, Y = data.x, data.y
    U, V = data.u[:,:,0], data.v[:,:,0] # first frame
    fig, ax = plt.subplots(1,1)
    M = np.sqrt(U**2 + V**2)
    
    Q = ax.quiver(X[::3,::3], Y[::3,::3], 
                  U[::3,::3], V[::3,::3], M[::3,::3],
                 units='inches', scale=arrowscale)
    
    cb = plt.colorbar(Q)
    
    units = data.attrs['units']
    
    cb.ax.set_ylabel('velocity (' + units[2] + ')')
    
    text = ax.text(0.2,1.05, '1/'+str(len(data.t)), ha='center', va='center',
                   transform=ax.transAxes)
    
    def update_quiver(num,Q,data,text):
        U,V = data.u[:,:,num],data.v[:,:,num]
        
        M = np.sqrt(U[::3,::3]**2 + V[::3,::3]**2)   
        Q.set_UVC(U,V,M)
        text.set_text(str(num+1)+'/'+str(len(data.t)))
        return Q

    anim = FuncAnimation(fig, update_quiver, fargs=(Q,data,text),
                               frames = len(data.t), blit=False)
    mywriter = FFMpegWriter()
    if savepath:
        p = os.getcwd()
        os.chdir(savepath)
        anim.save('im.mp4', writer=mywriter)
        os.chdir(p)
    else: anim.save('im.mp4', writer=mywriter)  
开发者ID:OpenPIV,项目名称:pivpy,代码行数:47,代码来源:graphics.py


示例20: start_timer

 def start_timer(self):
     self.system.ode_init()
     self.line, = self.axe.plot(self.system.x, -self.system.y, 
                                    "-o", animated=True)
     self.axe.set_xlim(-0.1, 1.1)
     self.axe.set_ylim(-1, 0.1)
     self.ani = FuncAnimation(self.figure, self.update_figure, 
                              blit=True, interval=20)
开发者ID:Andor-Z,项目名称:scpy2,代码行数:8,代码来源:catenary.py



注:本文中的matplotlib.animation.FuncAnimation类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python artist.kwdoc函数代码示例发布时间:2022-05-27
下一篇:
Python _pylab_helpers.Gcf类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap