Python matplotlib.animation.FuncAnimation() Examples

The following are 30 code examples of matplotlib.animation.FuncAnimation(). 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 also want to check out all available functions/classes of the module matplotlib.animation , or try the search function .
Example #1
Source File: movie.py    From kvae with MIT License 10 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 #2
Source File: tutorial.py    From feets with MIT License 8 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 #3
Source File: examples.py    From feets with MIT License 7 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 #4
Source File: utils.py    From tf2rl with MIT License 7 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 #5
Source File: traces.py    From Motiftoolbox with 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 #6
Source File: quadPlot.py    From quadcopter-simulation with 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 #7
Source File: display_methods.py    From indras_net with 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 #8
Source File: test.py    From Action-Recognition with 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 #9
Source File: traces.py    From Motiftoolbox with 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 #10
Source File: smoothlife.py    From SmoothLife with 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 #11
Source File: gpuGraph.py    From vins-application with 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 #12
Source File: test_animation.py    From neural-network-animation with 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 #13
Source File: ground_truth.py    From mvsec with 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 #14
Source File: simple_linear_regression.py    From deep-learning-samples with The Unlicense 5 votes vote down vote up
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() 
Example #15
Source File: manual.py    From wechat_jump_game with Apache License 2.0 5 votes vote down vote up
def action(self):
        self.figure.canvas.mpl_connect('button_press_event', self._onclick)
        ani = animation.FuncAnimation(self.figure, self._update_figure, interval=50, blit=True)
        plt.show() 
Example #16
Source File: create_video.py    From planet with Apache License 2.0 5 votes vote down vote up
def create_animation(frames, size, fps=10, **kwargs):
  fig = plt.figure(figsize=size, frameon=False)
  ax = fig.add_axes([0, 0, 1, 1])
  img = ax.imshow(frames[0], **kwargs)
  ax.set_xticks([])
  ax.set_yticks([])
  callback = lambda frame: (img, img.set_data(frame))[:1]
  kwargs = dict(frames=frames, interval=1000 / fps, blit=True)
  anim = animation.FuncAnimation(fig, callback, **kwargs)
  return anim 
Example #17
Source File: optimization_script.py    From affnet with MIT License 5 votes vote down vote up
def savemp4_per_desc(self, fname):
        if not os.path.isdir(self.loss_name):
            os.makedirs(self.loss_name)
        img = self.img1
        for d_idx in range(len(self.names_list)):
            fig, ax = plt.subplots()
            fig.set_tight_layout(True)
            ax.imshow(255 - img.squeeze())
            lines_dict = {}
            N = self.names_list[d_idx];
            C = self.colors[d_idx];
            lafs_dict = {"1": self.out_lafs1[N], "2": self.out_lafs2[N]}
            num_frames = len(lafs_dict["1"])
            lines_dict['1'], ax =  visualize_LAFs_on_fig(ax, lafs_dict["1"][0], 'r')
            lines_dict['2'], ax =  visualize_LAFs_on_fig(ax, lafs_dict["2"][0], 'b')
            ax.legend(['img1', 'img2'])
            def visualize_LAFs_on_fig_mod(laf_dict, line_dict, dname, i):
                work_LAFs = convertLAFs_to_A23format(laf_dict[dname][i])
                for jj in range(len(work_LAFs)):
                    ell = LAF2pts(work_LAFs[jj,:,:])
                    line_dict[dname][str(jj)].set_data(ell[:,0], ell[:,1])
                return line_dict[dname],ax
            def update_LAF(i):
                lines_dict["1"],ax =  visualize_LAFs_on_fig_mod(lafs_dict, lines_dict, "1", i)
                lines_dict["2"],ax =  visualize_LAFs_on_fig_mod(lafs_dict, lines_dict, "2", i)
                return lines_dict["1"], ax 
            anim = FuncAnimation(fig, update_LAF, frames=np.arange(0, num_frames), interval=75)
            Writer = animation.writers['ffmpeg']
            writer = Writer(fps=24, metadata=dict(artist='Me'), bitrate=900)
            anim.save(os.path.join(self.loss_name, N + "_" +  fname), dpi=72, writer=writer)
        return 
Example #18
Source File: optimization_script.py    From affnet with MIT License 5 votes vote down vote up
def savemp4_per_img(self, img, lafs_dict, fname):
        fig, ax = plt.subplots()
        fig.set_tight_layout(True)
        ax.imshow(255 - img.squeeze())
        lines_dict = {}
        for d_idx in range(len(self.names_list)):
            N = self.names_list[d_idx];
            C = self.colors[d_idx];
            num_frames = len(lafs_dict[N])
            lines_dict[N], ax =  visualize_LAFs_on_fig(ax, lafs_dict[N][0], C)
        ax.legend(self.names_list)
        def visualize_LAFs_on_fig_mod(laf_dict, line_dict, dname, i):
            work_LAFs = convertLAFs_to_A23format(laf_dict[dname][i])
            ells = []
            for jj in range(len(work_LAFs)):
                ell = LAF2pts(work_LAFs[jj,:,:])
                line_dict[dname][str(i)].set_data(ell[:,0], ell[:,1])
            return line_dict[dname],ax
        def update_LAF(i):
            for d_idx in range(len(self.names_list)):
                N = self.names_list[d_idx];
                C = self.colors[d_idx];
                lines_dict[N],ax =  visualize_LAFs_on_fig_mod(lafs_dict, lines_dict, N, i)
            return lines_dict[N], ax 
        ax.legend(self.names_list)
        anim = FuncAnimation(fig, update_LAF, frames=np.arange(0, num_frames), interval=75)
        import matplotlib.animation as animation
        Writer = animation.writers['ffmpeg']
        writer = Writer(fps=24, metadata=dict(artist='Me'), bitrate=1800)
        anim.save(fname, dpi=96, writer=writer)#'imagemagick')        
        return 
Example #19
Source File: visualization.py    From bindsnet with GNU Affero General Public License v3.0 5 votes vote down vote up
def plot_weights_movie(ws: np.ndarray, sample_every: int = 1) -> None:
    # language=rst
    """
    Create and plot movie of weights.
    
    :param ws: Array of shape ``[n_examples, source, target, time]``.
    :param sample_every: Sub-sample using this parameter.
    """
    weights = []

    # Obtain samples from the weights for every example.
    for i in range(ws.shape[0]):
        sub_sampled_weight = ws[i, :, :, range(0, ws[i].shape[2], sample_every)]
        weights.append(sub_sampled_weight)
    else:
        weights = np.concatenate(weights, axis=0)

    # Initialize plot.
    fig = plt.figure()
    im = plt.imshow(weights[0, :, :], cmap="hot_r", animated=True, vmin=0, vmax=1)
    plt.axis("off")
    plt.colorbar(im)

    # Update function for the animation.
    def update(j):
        im.set_data(weights[j, :, :])
        return [im]

    # Initialize animation.
    global ani
    ani = 0
    ani = animation.FuncAnimation(
        fig, update, frames=weights.shape[-1], interval=1000, blit=True
    )
    plt.show() 
Example #20
Source File: test_animation.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def make_animation(**kwargs):
    fig, ax = plt.subplots()
    line, = ax.plot([])

    def init():
        pass

    def animate(i):
        line.set_data([0, 1], [0, i])
        return line,

    return animation.FuncAnimation(fig, animate, **kwargs) 
Example #21
Source File: core.py    From auto_yolo with MIT License 5 votes vote down vote up
def _plot(self, updater, rollouts):
        plt.ion()

        if updater.dataset.gym_dataset.image_obs:
            obs = rollouts.obs
        else:
            obs = rollouts.image

        fig, axes = square_subplots(rollouts.batch_size, figsize=(5, 5))
        plt.subplots_adjust(top=0.95, bottom=0, left=0, right=1, wspace=0.1, hspace=0.1)

        images = []
        for i, ax in enumerate(axes.flatten()):
            ax.set_aspect("equal")
            ax.set_axis_off()
            image = ax.imshow(np.zeros(obs.shape[2:]))
            images.append(image)

        def animate(t):
            for i in range(rollouts.batch_size):
                images[i].set_array(obs[t, i, :, :, :])

        anim = animation.FuncAnimation(fig, animate, frames=len(rollouts), interval=500)

        path = updater.exp_dir.path_for('plots', '{}_animation.gif'.format(self.name))
        anim.save(path, writer='imagemagick')

        plt.close(fig) 
Example #22
Source File: animated_histogram.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def animate(i):
    # simulate new data coming in
    data = np.random.randn(1000)
    n, bins = np.histogram(data, 100)
    top = bottom + n
    verts[1::5, 1] = top
    verts[2::5, 1] = top
    return [patch, ]

###############################################################################
# And now we build the `Path` and `Patch` instances for the histogram using
# our vertices and codes. We add the patch to the `Axes` instance, and setup
# the `FuncAnimation` with our animate function. 
Example #23
Source File: GUI.py    From CT-GAN with MIT License 5 votes vote down vote up
def plot(self):
        self.ax.clear()
        if self.hist_state:
            self.im = self.ax.imshow(self.eq.equalize(self.manipulator.scan[self.ind,:,:]),cmap="bone")#, cmap="bone", vmin=-1000, vmax=1750)
        else:
            self.im = self.ax.imshow(self.manipulator.scan[self.ind,:,:], cmap="bone", vmin=-1000, vmax=1750)
        self.animation = animation.FuncAnimation(self.fig, self.animate, interval=100) 
Example #24
Source File: utils.py    From VNect with Apache License 2.0 5 votes vote down vote up
def plot_3d(q_start3d, q_joints, joint_parents):
    q_start3d.get()

    def joints_iter_gen_inner():
        while 1:
            yield q_joints.get(True)

    fig = plt.figure()
    ax = plt.axes(projection='3d')
    ani_update = PoseAnimation3d(ax, joint_parents)
    global ani
    ani = FuncAnimation(fig, ani_update, frames=joints_iter_gen_inner, init_func=ani_update.ani_init, interval=15,
                        blit=True)
    plt.show() 
Example #25
Source File: utils.py    From VNect with Apache License 2.0 5 votes vote down vote up
def plot_3d_init(joint_parents, joints_iter_gen):
    fig = plt.figure()
    ax = plt.axes(projection='3d')
    ani_update = PoseAnimation3d(ax, joint_parents)
    global ani
    ani = FuncAnimation(fig, ani_update, frames=joints_iter_gen, init_func=ani_update.ani_init, interval=20, blit=True)
    plt.ion()
    plt.show() 
Example #26
Source File: video_capture.py    From PyIntroduction with MIT License 5 votes vote down vote up
def pltCaputreVideo():
    capture = cv2.VideoCapture(0)

    if capture.isOpened() is False:
        raise("IO Error")

    def updateFrame(num, capture, image_plt):
        ret, image_bgr = capture.read()
        image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
        if ret == False:
            return image_plt,
        image_plt.set_array(image_rgb)
        return image_plt,

    ret, image_bgr = capture.read()
    if ret == False:
        capture.release()
        return

    fig = plt.figure()
    plt.title('Capture')
    image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)

    image_plt = plt.imshow(image_rgb, animated=True)
    plt.axis('off')
    ani = animation.FuncAnimation(fig, updateFrame, fargs=(capture, image_plt),
                                   interval=0, blit=True)
    plt.show()
    capture.release() 
Example #27
Source File: plotting.py    From orbital with MIT License 5 votes vote down vote up
def animate(self, orbit, speedup=5000, title=''):
        # Copy orbit, because it will be modified in the animation callback.
        orbit = copy(orbit)

        self.plot(orbit)

        num_points = self.points_per_rad * 2 * pi
        f = np.linspace(0, 2 * pi, num_points)

        def fpos(f):
            U, _, _ = uvw_from_elements(orbit.i, orbit.raan, orbit.arg_pe, f)
            pos = orbit_radius(orbit.a, orbit.e, f) * U
            pos /= kilo
            return pos[0], pos[1], pos[2]

        time_per_orbit = orbit.T / speedup
        interval = 1000 / 30
        times = np.linspace(orbit.t, orbit.t + orbit.T, time_per_orbit * 30)

        def animate(i):
            orbit.t = times[i - 1]
            x, y, z = fpos(orbit.f)
            self.pos_dot.set_data([x], [y])
            self.pos_dot.set_3d_properties([z])

            return self.pos_dot

        self.axes.set_title(title)

        # blit=True causes an error on OS X, disable for now.
        ani = animation.FuncAnimation(
            self.fig, animate, len(times), interval=interval, blit=False)

        return ani 
Example #28
Source File: plotting.py    From orbital with MIT License 5 votes vote down vote up
def animate(self, orbit, speedup=5000, title=''):
        # Copy orbit, because it will be modified in the animation callback.
        orbit = copy(orbit)

        self.plot(orbit)

        p = orbit.a * (1 - orbit.e ** 2)

        def fpos(f):
            pos = np.array([cos(f), sin(f), 0 * f]) * p / (1 + orbit.e * cos(f))
            pos /= kilo
            return pos

        time_per_orbit = orbit.T / speedup
        interval = 1000 / 30
        times = np.linspace(orbit.t, orbit.t + orbit.T, time_per_orbit * 30)

        def animate(i):
            orbit.t = times[i - 1]
            pos = fpos(orbit.f)
            self.pos_dot.set_data(pos[0], pos[1])

            return self.pos_dot

        self.axes.set_title(title)

        # blit=True causes an error on OS X, disable for now.
        ani = animation.FuncAnimation(
            self.fig, animate, len(times), interval=interval, blit=False)

        return ani 
Example #29
Source File: display_methods.py    From indras_net with 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 #30
Source File: vis_video.py    From models with MIT License 5 votes vote down vote up
def vis_video(imgs, repeat=False, ax=None, fig=None):
    """Visualize a video

    Returns:
        Animation
        
    """
    import matplotlib.pyplot as plt
    from matplotlib.animation import FuncAnimation

    if fig is None:
        fig = plt.figure()
        if ax is not None:
            raise ValueError('when ax is not None, fig should be not None')
    
    if ax is None:
        ax = fig.add_subplot(1, 1, 1)

    assert len(imgs) > 0

    img_ax = ax.imshow(imgs[0].transpose((1, 2, 0)).astype(np.uint8))

    def init():
        return img_ax,

    def update(img):
        img = img.transpose((1, 2, 0)).astype(np.uint8)
        img_ax.set_data(img)
        return img_ax,

    fps = 60
    ani = FuncAnimation(
        fig, update, frames=imgs[1:],
        init_func=init, blit=True, interval=1000/fps,
        repeat=repeat)

    return ani