Python matplotlib.animation.FuncAnimation() Examples

The following are 30 code examples for showing how to use matplotlib.animation.FuncAnimation(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may want to check out the right sidebar which shows the related API usage.

You may also want to check out all available functions/classes of the module matplotlib.animation , or try the search function .

Example 1
Project: indras_net   Author: gcallah   File: display_methods.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, title, varieties, data_points,
                 anim=False, data_func=None, is_headless=False, legend_pos=4):
        global anim_func

        self.title = title
        self.anim = anim
        self.data_func = data_func
        for i in varieties:
            data_points = len(varieties[i]["data"])
            break
        self.draw_graph(data_points, varieties)
        self.headless = is_headless

        if anim and not self.headless:
            anim_func = animation.FuncAnimation(self.fig,
                                    self.update_plot,
                                    frames=1000,
                                    interval=500,
                                    blit=False) 
Example 2
Project: quadcopter-simulation   Author: hbd730   File: quadPlot.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def plot_quad_3d(waypoints, get_world_frame):
    """
    get_world_frame is a function which return the "next" world frame to be drawn
    """
    fig = plt.figure()
    ax = fig.add_axes([0, 0, 1, 1], projection='3d')
    ax.plot([], [], [], '-', c='cyan')[0]
    ax.plot([], [], [], '-', c='red')[0]
    ax.plot([], [], [], '-', c='blue', marker='o', markevery=2)[0]
    ax.plot([], [], [], '.', c='red', markersize=4)[0]
    ax.plot([], [], [], '.', c='blue', markersize=2)[0]
    set_limit((-0.5,0.5), (-0.5,0.5), (-0.5,8))
    plot_waypoints(waypoints)
    an = animation.FuncAnimation(fig,
                                 anim_callback,
                                 fargs=(get_world_frame,),
                                 init_func=None,
                                 frames=400, interval=10, blit=False)

    if len(sys.argv) > 1 and sys.argv[1] == 'save':
        print "saving"
        an.save('sim.gif', dpi=80, writer='imagemagick', fps=60)
    else:
        plt.show() 
Example 3
Project: kvae   Author: simonkamronn   File: movie.py    License: MIT License 6 votes vote down vote up
def save_frames(images, filename):
    num_sequences, n_steps, w, h = images.shape

    fig = plt.figure()
    im = plt.imshow(combine_multiple_img(images[:, 0]), cmap=plt.cm.get_cmap('Greys'), interpolation='none')
    plt.axis('image')

    def updatefig(*args):
        im.set_array(combine_multiple_img(images[:, args[0]]))
        return im,

    ani = animation.FuncAnimation(fig, updatefig, interval=500, frames=n_steps)

    # Either avconv or ffmpeg need to be installed in the system to produce the videos!
    try:
        writer = animation.writers['avconv']
    except KeyError:
        writer = animation.writers['ffmpeg']
    writer = writer(fps=3)
    ani.save(filename, writer=writer)
    plt.close(fig) 
Example 4
Project: feets   Author: quatrope   File: tutorial.py    License: MIT License 6 votes vote down vote up
def ts_anim():
    # create a simple animation
    fig = plt.figure()
    ax = plt.axes(xlim=(0, 100), ylim=(-1, 1))
    Color = [ 1 ,0.498039, 0.313725];
    line, = ax.plot([], [], '*',color = Color)
    plt.xlabel("Time")
    plt.ylabel("Measurement")

    def init():
        line.set_data([], [])
        return line,

    def animate(i):
        x = np.linspace(0, i+1, i+1)
        ts = 5*np.cos(x * 0.02 * np.pi) * np.sin(np.cos(x)  * 0.02 * np.pi)
        line.set_data(x, ts)
        return line,

    return animation.FuncAnimation(fig, animate, init_func=init,
                                   frames=100, interval=200, blit=True) 
Example 5
Project: feets   Author: quatrope   File: examples.py    License: MIT License 6 votes vote down vote up
def basic_animation(frames=100, interval=30):
    """Plot a basic sine wave with oscillating amplitude"""
    fig = plt.figure()
    ax = plt.axes(xlim=(0, 10), ylim=(-2, 2))
    line, = ax.plot([], [], lw=2)

    x = np.linspace(0, 10, 1000)

    def init():
        line.set_data([], [])
        return line,

    def animate(i):
        y = np.cos(i * 0.02 * np.pi) * np.sin(x - i * 0.02 * np.pi)
        line.set_data(x, y)
        return line,

    return animation.FuncAnimation(fig, animate, init_func=init,
                                   frames=frames, interval=interval) 
Example 6
Project: Action-Recognition   Author: Naman-ntc   File: test.py    License: MIT License 6 votes vote down vote up
def main():
	global ax
	numframes = 100
	numpoints = 10
	#color_data = np.random.random((numframes, numpoints))
	data = np.random.random((numframes, 3, numpoints))*50

	fig = plt.figure()
	ax = fig.add_subplot(111, projection='3d')
	
	
	scat = ax.scatter(data[0,0,:], data[0,1,:], data[0,2,:], c='r', marker = 'o',alpha=0.5, s=100)

	ani = animation.FuncAnimation(fig, update_plot, frames= range(numframes),
	                              fargs=(data, scat))
	plt.show()


	# for i in range(100):
	# 	scat._offsets3d = juggle_axes(data[i,0,:], data[i,1,:], data[i,2,:], 'z')
	# 	for j in range(25):
	# 		ax.text(data[i,0,:], data[i,1,:], data[i,2,:], '%s' % (j)) 
	# 	fig.canvas.draw() 
Example 7
Project: tf2rl   Author: keiohta   File: utils.py    License: MIT License 6 votes vote down vote up
def frames_to_gif(frames, prefix, save_dir, interval=50, fps=30):
    """
    Convert frames to gif file
    """
    assert len(frames) > 0
    plt.figure(figsize=(frames[0].shape[1] / 72.,
                        frames[0].shape[0] / 72.), dpi=72)
    patch = plt.imshow(frames[0])
    plt.axis('off')

    def animate(i):
        patch.set_data(frames[i])

    # TODO: interval should be 1000 / fps ?
    anim = animation.FuncAnimation(
        plt.gcf(), animate, frames=len(frames), interval=interval)
    output_path = "{}/{}.gif".format(save_dir, prefix)
    anim.save(output_path, writer='imagemagick', fps=fps) 
Example 8
Project: SmoothLife   Author: duckythescientist   File: smoothlife.py    License: GNU General Public License v3.0 6 votes vote down vote up
def show_animation():
    w = 1 << 9
    h = 1 << 9
    # w = 1920
    # h = 1080
    sl = SmoothLife(h, w)
    sl.add_speckles()
    sl.step()

    fig = plt.figure()
    # Nice color maps: viridis, plasma, gray, binary, seismic, gnuplot
    im = plt.imshow(sl.field, animated=True,
                    cmap=plt.get_cmap("viridis"), aspect="equal")

    def animate(*args):
        im.set_array(sl.step())
        return (im, )

    ani = animation.FuncAnimation(fig, animate, interval=60, blit=True)
    plt.show() 
Example 9
Project: vins-application   Author: engcang   File: gpuGraph.py    License: GNU General Public License v3.0 6 votes vote down vote up
def updateGraph(frame):
    global fill_lines
    global gpuy_list
    global gpux_list
    global gpuLine
    global gpuAx

 
    # Now draw the GPU usage
    gpuy_list.popleft()
    with open(gpuLoadFile, 'r') as gpuFile:
      fileData = gpuFile.read()
    # The GPU load is stored as a percentage * 10, e.g 256 = 25.6%
    gpuy_list.append(int(fileData)/10)
    gpuLine.set_data(gpux_list,gpuy_list)
    fill_lines.remove()
    fill_lines=gpuAx.fill_between(gpux_list,0,gpuy_list, facecolor='cyan', alpha=0.50)

    return [gpuLine] + [fill_lines]


# Keep a reference to the FuncAnimation, so it does not get garbage collected 
Example 10
Project: neural-network-animation   Author: miloharper   File: test_animation.py    License: MIT License 6 votes vote down vote up
def test_no_length_frames():
    fig, ax = plt.subplots()
    line, = ax.plot([], [])

    def init():
        line.set_data([], [])
        return line,

    def animate(i):
        x = np.linspace(0, 10, 100)
        y = np.sin(x + i)
        line.set_data(x, y)
        return line,

    anim = animation.FuncAnimation(fig, animate, init_func=init,
                                   frames=iter(range(5))) 
Example 11
Project: mvsec   Author: daniilidis-group   File: ground_truth.py    License: MIT License 6 votes vote down vote up
def play_image(self):
        import numpy as np
        import matplotlib.pyplot as plt
        import matplotlib.animation as animation
        fig = plt.figure()
        left_cam = self.left_cam_readers['/davis/left/depth_image_raw']
        
        first_view = left_cam[0]
        first_view.acquire()
        im = plt.imshow(first_view.img, animated=True)
        #first_view.release()
        
        def updatefig(frame_num, *args):
            view = left_cam[frame_num]
            view.acquire()
            im.set_data(view.img)
            return im,
        
        ani = animation.FuncAnimation(fig, updatefig, frames=len(left_cam), blit=True)
        ani.save("test.mp4")
        plt.show() 
Example 12
Project: Motiftoolbox   Author: jusjusjus   File: traces.py    License: GNU General Public License v2.0 6 votes vote down vote up
def on_click(self, event):

		if event.inaxes == self.ax and self.running == False:

		        self.params = model.params_three()
		        self.coupling = np.zeros((9), float)
		        self.coupling[:6] = self.network.coupling_strength
		        length = self.system.N_output(self.CYCLES)
		        self.t = self.system.dt*np.arange(length)
		        self.trajectory = np.zeros((length, 3), float)

		        self.li_b.set_data(self.t, self.trajectory[:, 0])
		        self.li_g.set_data(self.t, self.trajectory[:, 1]-0.06)
		        self.li_r.set_data(self.t, self.trajectory[:, 2]-0.12)

			ticks = np.asarray(self.t[::self.t.size/10], dtype=int)
			self.ax.set_xticks(ticks)
			self.ax.set_xticklabels(ticks)
                        self.ax.set_xlim(self.t[0], self.t[-1])

                        self.fig.canvas.draw()

                        self.anim = animation.FuncAnimation(self.fig, self.compute_step, init_func=self.init, frames=self.trajectory.shape[0], interval=0, blit=True, repeat=False)

			self.running = True 
Example 13
Project: Motiftoolbox   Author: jusjusjus   File: traces.py    License: GNU General Public License v2.0 6 votes vote down vote up
def on_click(self, event):

		if event.inaxes == self.ax:

		        self.params = model.parameters_n()
		        self.g_inh = model.params['g_inh_0']

		        length = self.system.N_output(self.CYCLES)
		        self.t = self.system.dt*np.arange(length)
		        self.trajectory = np.zeros((length, self.num_osci), float)

                        for i in xrange(self.num_osci):
		            self.li[i].set_data(self.t, self.trajectory[:, i]-i*2.)

			ticks = np.asarray(self.t[::self.t.size/10], dtype=int)
			self.ax.set_xticks(ticks)
			self.ax.set_xticklabels(ticks)
                        self.ax.set_xlim(self.t[0], self.t[-1])

                        self.fig.canvas.draw()

                        self.anim = animation.FuncAnimation(self.fig, self.compute_step, init_func=self.init, frames=self.trajectory.shape[0], interval=0, blit=True, repeat=False) 
Example 14
Project: indras_net   Author: gcallah   File: display_methods.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, title, varieties, width, height,
                 anim=True, data_func=None, is_headless=False, legend_pos=4):
        """
        Setup a scatter plot.
        varieties contains the different types of
        entities to show in the plot, which
        will get assigned different colors
        """
        global anim_func

        self.scats = None
        self.anim = anim
        self.data_func = data_func
        self.s = ceil(4096 / width)
        self.headless = is_headless

        fig, ax = plt.subplots()
        ax.set_xlim(0, width)
        ax.set_ylim(0, height)
        self.create_scats(varieties)
        ax.legend(loc = legend_pos)
        ax.set_title(title)
        plt.grid(True)

        if anim and not self.headless:
            anim_func = animation.FuncAnimation(fig,
                                    self.update_plot,
                                    frames=1000,
                                    interval=500,
                                    blit=False) 
Example 15
Project: pepper-robot-programming   Author: maverickjoy   File: asthama_search.py    License: MIT License 5 votes vote down vote up
def run(self):
        self._printLogs("Waiting for the robot to be in wake up position", "OKBLUE")

        self.motion_service.wakeUp()
        self.posture_service.goToPosture("StandInit", 0.1)

        self.create_callbacks()
        # self.startDLServer()
        self._addTopic()

        # graphplots
        self._initialisePlot()
        ani = animation.FuncAnimation(self.fig, self._animate, blit=False, interval=500 ,repeat=False)


        # loop on, wait for events until manual interruption
        try:
            # while True:
            #     time.sleep(1)
            # starting graph plot
            plt.show() # blocking call hence no need for while(True)

        except KeyboardInterrupt:
            self._printLogs("Interrupted by user, shutting down", "FAIL")
            self._cleanUp()

            self._printLogs("Waiting for the robot to be in rest position", "FAIL")
            # self.motion_service.rest()
            sys.exit(0)

        return 
Example 16
Project: kvae   Author: simonkamronn   File: movie.py    License: MIT License 5 votes vote down vote up
def save_true_generated_frames(true, generated, filename):
    num_sequences, n_steps, w, h = true.shape

    # Background is 0, foreground as 1
    true = np.copy(true[:16])
    true[true > 0.1] = 1

    # Set foreground be near 0.5
    generated = generated * .5

    # Background is 1, foreground is near 0.5
    generated = 1 - generated[:16, :n_steps]

    # Subtract true from generated so background is 1, true foreground is 0,
    # and generated foreground is around 0.5
    images = generated - true
    # images[images > 0.5] = 1.

    fig = plt.figure()
    im = plt.imshow(combine_multiple_img(images[:, 0]), cmap=plt.cm.get_cmap('gist_heat'),
                    interpolation='none', vmin=0, vmax=1)
    plt.axis('image')

    def updatefig(*args):
        im.set_array(combine_multiple_img(images[:, args[0]]))
        return im,

    ani = animation.FuncAnimation(fig, updatefig, interval=500, frames=n_steps)

    try:
        writer = animation.writers['avconv']
    except KeyError:
        writer = animation.writers['ffmpeg']
    writer = writer(fps=3)
    ani.save(filename, writer=writer)
    plt.close(fig) 
Example 17
Project: pulse2percept   Author: pulse2percept   File: test_base.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_Percept_play(n_frames):
    ndarray = np.random.rand(2, 4, n_frames)
    percept = Percept(ndarray)
    ani = percept.play()
    npt.assert_equal(isinstance(ani, FuncAnimation), True)
    npt.assert_equal(len(list(ani.frame_seq)), n_frames) 
Example 18
Project: Eins   Author: xiongbeer   File: testplot.py    License: MIT License 5 votes vote down vote up
def plot():
    'Waring: Cannot stop this,once started'
    anim = FuncAnimation(layer.getLayer(), update, interval = 10)
    plt.show()
#---------------------------------------------------------------------------- 
Example 19
Project: dgl   Author: dmlc   File: viz.py    License: Apache License 2.0 5 votes vote down vote up
def att_animation(maps_array, mode, src, tgt, head_id):
    weights = [maps[mode2id[mode]][head_id] for maps in maps_array]
    fig, axes = plt.subplots(1, 2)

    def weight_animate(i):
        global colorbar
        if colorbar:
            colorbar.remove()
        plt.cla()
        axes[0].set_title('heatmap')
        axes[0].set_yticks(np.arange(len(src)))
        axes[0].set_xticks(np.arange(len(tgt)))
        axes[0].set_yticklabels(src)
        axes[0].set_xticklabels(tgt)
        plt.setp(axes[0].get_xticklabels(), rotation=45, ha="right",
                 rotation_mode="anchor")

        fig.suptitle('epoch {}'.format(i))
        weight = weights[i].transpose(-1, -2)
        heatmap = axes[0].pcolor(weight, vmin=0, vmax=1, cmap=plt.cm.Blues)
        colorbar = plt.colorbar(heatmap, ax=axes[0], fraction=0.046, pad=0.04)
        axes[0].set_aspect('equal')
        axes[1].axis("off")
        graph_att_head(src, tgt, weight, axes[1], 'graph')


    ani = animation.FuncAnimation(fig, weight_animate, frames=len(weights), interval=500, repeat_delay=2000)
    return ani 
Example 20
Project: Qualia2.0   Author: Kashu7100   File: rl_core.py    License: MIT License 5 votes vote down vote up
def animate(self, frames, filename):
        plt.clf()
        plt.figure(figsize=(frames[0].shape[1]/72.0, frames[0].shape[0]/72.0), dpi=72)
        result = plt.imshow(frames[0])
        plt.axis('off')
        video = animation.FuncAnimation(plt.gcf(), lambda t: result.set_data(frames[t]), frames=len(frames), interval=50)
        video.save(filename+'.mp4')
        plt.close() 
Example 21
Project: openplotter   Author: sailoog   File: SDR_AIS_waterfall.py    License: GNU General Public License v2.0 5 votes vote down vote up
def start(self):
        self.update_plot_labels()
        if sys.platform == 'darwin':
            # Disable blitting. The matplotlib.animation's restore_region()
            # method is only implemented for the Agg-based backends,
            # which the macosx backend is not.
            blit = False
        else:
            blit = True
        ani = animation.FuncAnimation(self.fig, self.update, interval=50,
                blit=blit)

        pyl.show()

        return 
Example 22
Project: pyswarms   Author: ljvmiranda921   File: plotters.py    License: MIT License 5 votes vote down vote up
def _animate(i, data, plot):
    """Helper animation function that is called sequentially
    :class:`matplotlib.animation.FuncAnimation`
    """
    current_pos = data[i]
    if np.array(current_pos).shape[1] == 2:
        plot.set_offsets(current_pos)
    else:
        plot._offsets3d = current_pos.T
    return (plot,) 
Example 23
Project: pyswarms   Author: ljvmiranda921   File: test_plotters.py    License: MIT License 5 votes vote down vote up
def test_plot_contour_return_type(pos_history):
    """Tests if the animation function returns the expected type"""
    assert isinstance(plot_contour(pos_history), FuncAnimation) 
Example 24
Project: pyswarms   Author: ljvmiranda921   File: test_plotters.py    License: MIT License 5 votes vote down vote up
def test_plot_surface_return_type(pos_history):
    """Tests if the animation function returns the expected type"""
    assert isinstance(plot_surface(pos_history), FuncAnimation) 
Example 25
Project: enzynet   Author: shervinea   File: real_time.py    License: MIT License 5 votes vote down vote up
def animate(self, figure, callback, interval=50):
        import matplotlib.animation as animation
        def wrapper(frame_index):
            self.add(*callback(frame_index))
            self.axes.relim(); self.axes.autoscale_view() # Rescale the y-axis
            return self.lineplot
        animation.FuncAnimation(figure, wrapper, interval=interval) 
Example 26
Project: seagull   Author: ljvmiranda921   File: test_simulator.py    License: MIT License 5 votes vote down vote up
def test_simulator_animate():
    """Test if animate() method returns a FuncAnimation"""
    board = sg.Board(size=(10, 10))
    board.add(lf.Blinker(length=3), loc=(0, 1))
    sim = sg.Simulator(board)
    sim.run(sg.rules.conway_classic, iters=10)
    anim = sim.animate()
    assert isinstance(anim, animation.FuncAnimation) 
Example 27
Project: kits19.MIScnn   Author: muellerdo   File: visualizer.py    License: GNU General Public License v3.0 5 votes vote down vote up
def visualize_evaluation(case_id, vol, truth, pred, eva_path):
    # Color volumes according to truth and pred segmentation
    vol_truth = overlay_segmentation(vol, truth)
    vol_pred = overlay_segmentation(vol, pred)
    # Create a figure and two axes objects from matplot
    fig, (ax1, ax2) = plt.subplots(1, 2)
    # Initialize the two subplots (axes) with an empty 512x512 image
    data = np.zeros(vol.shape[1:3])
    ax1.set_title("Ground Truth")
    ax2.set_title("Prediction")
    img1 = ax1.imshow(data)
    img2 = ax2.imshow(data)
    # Update function for both images to show the slice for the current frame
    def update(i):
        plt.suptitle("Case ID: " + str(case_id) + " - " + "Slice: " + str(i))
        img1.set_data(vol_truth[i])
        img2.set_data(vol_pred[i])
        return [img1, img2]
    # Compute the animation (gif)
    ani = animation.FuncAnimation(fig, update, frames=len(truth), interval=10,
                                  repeat_delay=0, blit=False)
    # Set up the output path for the gif
    if not os.path.exists(eva_path):
        os.mkdir(eva_path)
    file_name = "visualization.case_" + str(case_id).zfill(5) + ".gif"
    out_path = os.path.join(eva_path, file_name)
    # Save the animation (gif)
    ani.save(out_path, writer='imagemagick', fps=30)
    # Close the matplot
    plt.close()


#-----------------------------------------------------#
#                     Subroutines                     #
#-----------------------------------------------------#
# Based on: https://github.com/neheller/kits19/blob/master/starter_code/visualize.py 
Example 28
Project: eht-imaging   Author: achael   File: starwarps.py    License: GNU General Public License v3.0 5 votes vote down vote up
def movie(im_List, out='movie.mp4', fps=10, dpi=120):
    import matplotlib
    matplotlib.use('agg')
    import matplotlib.pyplot as plt
    import matplotlib.animation as animation

    fig = plt.figure()
    frame = im_List[0].imvec #read_auto(filelist[len(filelist)/2])
    fov = im_List[0].psize*im_List[0].xdim
    extent = fov * np.array((1,-1,-1,1)) / 2.
    maxi = np.max(frame)
    im = plt.imshow( np.reshape(frame,[im_List[0].xdim, im_List[0].xdim]) , cmap='hot', extent=extent) #inferno
    plt.colorbar()
    im.set_clim([0,maxi])
    fig.set_size_inches([5,5])
    plt.tight_layout()

    def update_img(n):
        sys.stdout.write('\rprocessing image %i of %i ...' % (n,len(im_List)) )
        sys.stdout.flush()
        im.set_data(np.reshape(im_List[n].imvec, [im_List[n].xdim, im_List[n].xdim]) )
        return im

    ani = animation.FuncAnimation(fig,update_img,len(im_List),interval=1e3/fps)
    writer = animation.writers['ffmpeg'](fps=max(20, fps), bitrate=1e6)
    ani.save(out,writer=writer,dpi=dpi) 
Example 29
Project: viznet   Author: GiggleLiu   File: context.py    License: MIT License 5 votes vote down vote up
def __exit__(self, exc_type, exc_val, traceback):
        if traceback is not None:
            return False
        plt.axis('equal')
        plt.axis('off')
        plt.tight_layout()
        if self.filename[-4:] == ".gif":
            nframe = len(self.steps)+1

            def update(i):
                if i!=0:
                    self.steps[i-1]()

            anim = FuncAnimation(plt.gcf(), update, frames=range(nframe), repeat=False)
            print('Press `c` to save figure to "%s", `Ctrl+d` to break >>' %
                    self.filename)
            anim.save(self.filename, writer="imagemagick", fps=self.fps)
        elif self.filename is not None:
            for f in self.steps:
                f()
            print('Press `c` to save figure to "%s", `Ctrl+d` to break >>' %
                  self.filename)
            pdb.set_trace()
            plt.savefig(self.filename, dpi=300, transparent=True)
        else:
            pdb.set_trace()
        return True 
Example 30
Project: SpaceXtract   Author: shahar603   File: plot_raw_telemetry.py    License: MIT License 5 votes vote down vote up
def animate_graph():
    fig = plt.figure()
    global ax1
    ax1 = fig.add_subplot(1,1,1)
    ani = animation.FuncAnimation(fig, animate, interval=100)
    plt.show()