我们从Python开源项目中,提取了以下27个代码示例,用于说明如何使用matplotlib.animation()。
def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.configure(bg=BG_COLOR) self.trends = Figure(figsize=(5, 5), dpi=100) self.a = self.trends.add_subplot(111) canvas = FigureCanvasTkAgg(self.trends, self) canvas.show() canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1) toolbar = NavigationToolbar2TkAgg(canvas, self) toolbar.update() canvas._tkcanvas.pack(side=tk.BOTTOM, fill=tk.BOTH, expand=1) self.animation = FuncAnimation(self.trends, self.animate, 5000)
def initialize(self): self.fig = plt.figure() self.axes_dict = self.create_fig(self.fig) for plot_key in self.plot_layers.keys(): plot_layer = self.plot_layers[plot_key] if plot_key not in self.axes_dict: raise KeyError("No axis created for plot %s" % plot_key) plot_layer.create_fig(self.fig, self.axes_dict[plot_key]) # matplotlib.animation.Animation._blit_draw = _blit_draw self.anim = animation.FuncAnimation(self.fig, self.update_func, init_func=self.init_func, frames=None, interval=1000 / self.fps, blit=True) print("show") plt.ion() plt.show() print("continue")
def plot_hist(str_name, save_name='dist'): data_array = utils.get_data(str_name) params = np.squeeze(np.array(data_array['information'])) ind_array = data_array['params']['epochsInds'] DKL_YgX_YgT = utils.extract_array(params, 'DKL_YgX_YgT') p_ts = utils.extract_array(params, 'pts') H_Xgt = utils.extract_array(params, 'H_Xgt') f, (axes) = plt.subplots(3, 1) #axes = [axes] f.subplots_adjust(left=0.14, bottom=0.1, right=.928, top=0.94, wspace=0.13, hspace=0.55) colors = LAYERS_COLORS line_ani = animation.FuncAnimation(f, update_bars_num_of_ts, len(p_ts), repeat=False, interval=1, blit=False, fargs=[p_ts,H_Xgt,DKL_YgX_YgT, axes,ind_array]) Writer = animation.writers['ffmpeg'] writer = Writer(fps=50) #Save the movie line_ani.save(save_name+'_movie.mp4',writer=writer,dpi=250) plt.show()
def main(): print('plotting data...') analogPlot = AnalogPlot(200) # set up animation fig = plt.figure() ax = plt.axes(xlim=(0, 200), ylim=(-1000, 8000)) a0, = ax.plot([], []) a1, = ax.plot([], []) anim = animation.FuncAnimation(fig, analogPlot.update, fargs=(a0, a1), interval=40, frames=300, blit=True) plt.show() # anim.save('animation.mp4', fps=30, # extra_args=['-vcodec', 'libx264']) print('exiting.') # call main
def __init__(self, sim, fig, grid=[3, 3], display_interval=100, type_to_color=None): """ Create new animation showing results of molecular dynamics simulation :param sim: simulation instance :param fig: matplotlib figure :param grid: size of the plot grid, i.e. how many spaces where plots can be positioned to :param display_interval: how many time steps to run before a new animation frame is drawn :param type_to_color: array of matplotlib colors ith same length as there are particle types in the simulation, mapping each particle type to a color """ self._sim = sim self._fig = fig self._display_interval = display_interval self._animators = [] self._grid_spec = matplotlib.gridspec.GridSpec(*grid) self._type_to_color = type_to_color self._frame_callbacks = [] if not self._type_to_color: self._type_to_color = get_default_particle_colors(sim.nr_of_atom_types)
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)
def writevideo(self): #print animation.writers.list() #matplotlib.rcParams['animation.ffmpeg_args'] = ['-report', '/tmp/ffmpeg.log'] #FFMpegWriter = animation.writers['ffmpeg'] metadata = dict(title='Github Data Projects', artist='0x0FFF', comment='Evolution of open source data projects') writer = FFMpegWriter(fps=30, bitrate=8000, metadata=metadata ) i = 0 #self.iters = 200 with writer.saving(self.fig, "/projects/personal/writer_test.mp4", 120): while i < self.iters: self.update_animation(i) writer.grab_frame() i += 1 return
def theta_anim(self): # # Animate the contour plot from above by varying theta from 0 to 2*pi # self.theta = 0 x,y,z = self.location_contours([0.2, 0.2, 0.2, self.theta]) self.fig = plt.figure() self.im = plt.imshow(z, interpolation='bilinear', origin='lower', cmap=cm.inferno) CBI = plt.colorbar(self.im, orientation='horizontal', shrink=0.8) plt.title('Contour Plot - Q') ani = animation.FuncAnimation(self.fig, self.update_theta, interval=50, blit=False) plt.show()
def theta_gif(self): # # Create an animated gif of the contour plot from above by varying theta from 0 to pi # self.theta = 0 x,y,z = self.location_contours([0.2, 0.2, 0.2, self.theta]) self.fig = plt.figure() self.im = plt.imshow(z, interpolation='bilinear', origin='lower', cmap=cm.inferno) CBI = plt.colorbar(self.im, orientation='horizontal', shrink=0.8) plt.xlabel('X %') plt.ylabel('Y %') ani = animation.FuncAnimation(self.fig, self.update_theta, frames=np.arange(0,20), interval=200, blit=False) ani.save('figures/theta.gif', dpi=80, writer='imagemagick')
def sensor_anim(self, theta=0): # # Animate the contour plot by changing sensor values and holding # the angle fixed at theta. # self.theta = theta self.sensor = 0.0 x,y,z = self.location_contours([0,0,0, self.theta]) self.fig = plt.figure() self.im = plt.imshow(z, interpolation='bilinear', origin='lower', cmap=cm.inferno) CBI = plt.colorbar(self.im, orientation='horizontal', shrink=0.8) ani = animation.FuncAnimation(self.fig, self.update_sensor, interval=50, blit=False) plt.show()
def __init__(self, t, fig, axim, tracker, occ, pt_xz, pt_zy, body, bodies, occultors, interval = 50, gifname = None, xy = None, quiet = False): ''' ''' self.t = t self.fig = fig self.axim = axim self.tracker = tracker self.occ = occ self.pt_xz = pt_xz self.pt_zy = pt_zy self.body = body self.bodies = bodies self.occultors = occultors self.xy = xy self.pause = True self.animation = animation.FuncAnimation(self.fig, self.animate, frames = 100, interval = interval, repeat = True) # Save? if gifname is not None: self.pause = False if not gifname.endswith('.gif'): gifname += '.gif' if not quiet: print("Saving %s..." % gifname) self.animation.save(gifname, writer = 'imagemagick', fps = 20, dpi = 150) self.pause = True # Toggle button self.axbutton = pl.axes([0.185, 0.12, 0.1, 0.03]) self.button = Button(self.axbutton, 'Play', color = 'lightgray') self.button.on_clicked(self.toggle)
def toggle(self, event): ''' Pause/play the animation. Unfortunately I haven't been able to figure out how to freeze the animation so that it resumes at the same frame it was paused on... ''' if self.pause: self.button.label.set_text('Pause') else: self.button.label.set_text('Play') self.pause ^= True
def animate(self, j): ''' Play frame `j` of the animation. ''' if not self.pause: # Normalize the time index j = int(j * len(self.t) / 100.) # Time tracker self.tracker.set_xdata(self.bodies[0].time_hr[self.t[j]]) # Occultor images x0 = self.body.x_hr[self.t[j]] y0 = self.body.y_hr[self.t[j]] for k, occultor in enumerate(self.occultors): if self.xy is None: xo, yo = occultor.x_hr[self.t[j]] - x0, \ occultor.y_hr[self.t[j]] - y0 else: xo, yo = self.xy(occultor.x_hr[self.t[j]] - x0, occultor.y_hr[self.t[j]] - y0) self.occ[k].center = (xo / self.body._r, yo / self.body._r) # BODY orbits for k, b in enumerate(self.bodies): self.pt_xz[k].set_xdata(b.x_hr[self.t[j]]) self.pt_xz[k].set_ydata(b.z_hr[self.t[j]]) self.pt_zy[k].set_xdata(b.z_hr[self.t[j]]) self.pt_zy[k].set_ydata(b.y_hr[self.t[j]])
def initialize(self): self.fig = plt.figure() self.axes_dict = self.create_fig(self.fig) for plot_key in self.plot_layers.keys(): plot_layer = self.plot_layers[plot_key] if plot_key not in self.axes_dict: raise KeyError("No axis created for plot %s" % plot_key) plot_layer.create_fig(self.fig, self.axes_dict[plot_key]) # matplotlib.animation.Animation._blit_draw = _blit_draw self.anim = animation.FuncAnimation(self.fig, self.update_func, init_func=self.init_func, frames=None, interval=1000 / self.fps, blit=True)
def plot_animation(name_s, save_name): """Plot the movie for all the networks in the information plane""" # If we want to print the loss function also print_loss = False #The bins that we extened the x axis of the accuracy each time epochs_bins = [0, 500, 1500, 3000, 6000, 10000, 20000] data_array = utils.get_data(name_s[0][0]) data = data_array['infomration'] epochsInds = data_array['epochsInds'] loss_train_data = data_array['loss_train'] loss_test_data = data_array['loss_test_data'] f, (axes) = plt.subplots(2, 1) f.subplots_adjust(left=0.14, bottom=0.1, right=.928, top=0.94, wspace=0.13, hspace=0.55) colors = LAYERS_COLORS #new/old version if False: Ix = np.squeeze(data[0,:,-1,-1, :, :]) Iy = np.squeeze(data[1,:,-1,-1, :, :]) else: Ix = np.squeeze(data[0, :, -1, -1, :, :])[np.newaxis,:,:] Iy = np.squeeze(data[1, :, -1, -1, :, :])[np.newaxis,:,:] #Interploation of the samplings (because we don't cauclaute the infomration in each epoch) interp_data_x = interp1d(epochsInds, Ix, axis=1) interp_data_y = interp1d(epochsInds, Iy, axis=1) new_x = np.arange(0,epochsInds[-1]) new_data = np.array([interp_data_x(new_x), interp_data_y(new_x)]) """" train_data = interp1d(epochsInds, np.squeeze(train_data), axis=1)(new_x) test_data = interp1d(epochsInds, np.squeeze(test_data), axis=1)(new_x) """ if print_loss: loss_train_data = interp1d(epochsInds, np.squeeze(loss_train_data), axis=1)(new_x) loss_test_data=interp1d(epochsInds, np.squeeze(loss_test_data), axis=1)(new_x) line_ani = animation.FuncAnimation(f, update_line, len(new_x), repeat=False, interval=1, blit=False, fargs=(print_loss, new_data, axes,new_x,train_data,test_data,epochs_bins, loss_train_data,loss_test_data, colors)) Writer = animation.writers['ffmpeg'] writer = Writer(fps=100) #Save the movie line_ani.save(save_name+'_movie2.mp4',writer=writer,dpi=250) plt.show()
def plot_animation_each_neuron(name_s, save_name, print_loss=False): """Plot the movie for all the networks in the information plane""" # If we want to print the loss function also #The bins that we extened the x axis of the accuracy each time epochs_bins = [0, 500, 1500, 3000, 6000, 10000, 20000] data_array = utils.get_data(name_s[0][0]) data = np.squeeze(data_array['information']) f, (axes) = plt.subplots(1, 1) axes = [axes] f.subplots_adjust(left=0.14, bottom=0.1, right=.928, top=0.94, wspace=0.13, hspace=0.55) colors = LAYERS_COLORS #new/old version Ix = np.squeeze(data[0,:, :, :]) Iy = np.squeeze(data[1,:, :, :]) #Interploation of the samplings (because we don't cauclaute the infomration in each epoch) #interp_data_x = interp1d(epochsInds, Ix, axis=1) #interp_data_y = interp1d(epochsInds, Iy, axis=1) #new_x = np.arange(0,epochsInds[-1]) #new_data = np.array([interp_data_x(new_x), interp_data_y(new_x)]) """" train_data = interp1d(epochsInds, np.squeeze(train_data), axis=1)(new_x) test_data = interp1d(epochsInds, np.squeeze(test_data), axis=1)(new_x) if print_loss: loss_train_data = interp1d(epochsInds, np.squeeze(loss_train_data), axis=1)(new_x) loss_test_data=interp1d(epochsInds, np.squeeze(loss_test_data), axis=1)(new_x) """ line_ani = animation.FuncAnimation(f, update_line_each_neuron, Ix.shape[1], repeat=False, interval=1, blit=False, fargs=(print_loss, Ix, axes,Iy,train_data,test_data,epochs_bins, loss_train_data,loss_test_data, colors,epochsInds)) Writer = animation.writers['ffmpeg'] writer = Writer(fps=100) #Save the movie line_ani.save(save_name+'_movie.mp4',writer=writer,dpi=250) plt.show()
def __init__(self, parent, status, title): ttk.Frame.__init__(self, parent) self.status = status self.canvas = FigureCanvasTkAgg(status.figure, self) self.canvas.show() self.canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True) self.animation = animation.FuncAnimation(status.figure, lambda i : status.update_plots(i), interval=1000)
def animation(agents, function, lb, ub, sr=False): side = np.linspace(lb, ub, (ub - lb) * 5) X, Y = np.meshgrid(side, side) Z = np.array([np.array([function([X[i][j], Y[i][j]]) for j in range(len(X))]) for i in range(len(X[0]))]) fig = plt.figure() plt.axes(xlim=(lb, ub), ylim=(lb, ub)) plt.pcolormesh(X, Y, Z, shading='gouraud') plt.colorbar() x = np.array([j[0] for j in agents[0]]) y = np.array([j[1] for j in agents[0]]) sc = plt.scatter(x, y, color='black') plt.title(function.__name__, loc='left') def an(i): x = np.array([j[0] for j in agents[i]]) y = np.array([j[1] for j in agents[i]]) sc.set_offsets(list(zip(x, y))) plt.title('iteration: {}'.format(i), loc='right') ani = matplotlib.animation.FuncAnimation(fig, an, frames=len(agents) - 1) if sr: ani.save('result.mp4') plt.show()
def main(argv): dataFolder = '' particlesFile = '' numberOfParticles = 0 outputFile = "animation" usage = 'ParticleFilterVisualizer.py -f <dataFolder> -p <particleFile> -n <numberOfParticles> [-o <outputFileName>]' try: opts, args = getopt.getopt(argv,"hf:p:n:o:",["dataFolder=","particleFile=","numberParticles=" ,"outPutFile="]) except getopt.GetoptError: print(usage) sys.exit(2) if len(opts) is 0: print(usage) sys.exit() for opt, arg in opts: if opt == '-h': print(usage) sys.exit() elif opt in ("-f", "--dataFolder"): dataFolder = arg elif opt in ("-p", "--particleFile"): particlesFile = arg elif opt in ("-n", "--numberOfParticles"): numberOfParticles = arg elif opt in ("-o", "--outputFile"): outputFile = arg else: print(usage) sys.exit(2) plotData(dataFolder, particlesFile, numberOfParticles, outputFile)
def get_animation_object(self, **kwargs): """Returns matplotlib FuncAnimation object - use this e.g. to store animation as video""" self.__update() return animation.FuncAnimation(self._fig, self.__update, **kwargs)
def run(self, final_frame_name=None, dpi=300): """ Starts the visualization process. If the property `out_filename` is set, the visualization is saved as a video to the disk; if not, the animation is displayed on screen. Please refer to documentation of `add_LPU`, `add_plot` and the properties of this class on how to configure the visualizer before calling this method. An example can be found in the class doc string. Parameters ---------- final_frame_name : str, optional If specified, the final frame of the animation is saved to disk. dpi : int, default=300 Resolution at which final frame is saved to disk if `final_frame_name` is specified. Notes ----- If `update_interval` is set to 0 or None, it will be replaced by the index of the final time step. As a result, the visualizer will only generate and save the final frame if `final_frame_name` is set. """ self.final_frame_name = final_frame_name self._initialize() if not self._update_interval: self._update_interval = self._maxt self._t = self._maxt if self._update_interval == -1: self._update_interval = max(np.asarray(self._dts.values()))*50 for _ in np.arange(self._t,self._maxt*(1+np.finfo(float).eps), self._update_interval): self._update() if final_frame_name is not None: self.f.savefig(final_frame_name, dpi=dpi) if self.out_filename: self._close()
def update_interval(self): """ Update interval (in unit of time same as dt in the h5 files) for the animation. """ return self._update_interval
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)
def make_aia_animation(aia, start_time: u.s, stop_time: u.s, root_dir, figsize=None, norm=None, fontsize=14, **kwargs): """ Build animation from a series of synthesized AIA observations """ with h5py.File(aia.counts_file, 'r') as hf: reference_time = u.Quantity(hf['time'], hf['time'].attrs['units']) start_index = np.where(reference_time == start_time)[0][0] stop_index = np.where(reference_time == stop_time)[0][0] fig_format = os.path.join(root_dir, f'{aia.name}', '{}', 'map_t{:06d}.fits') fig, ims = plot_aia_channels(aia, start_time, root_dir, figsize=figsize, norm=norm, fontsize=fontsize, use_with_animation=True) def update_fig(i): for channel in aia.channels: tmp = Map(fig_format.format(channel['name'], i)) ims[channel['name']].set_array(tmp.data) fig.suptitle(r'$t={:.0f}$ {}'.format(reference_time[i].value, reference_time.unit.to_string()), fontsize=fontsize) return [ims[k] for k in ims] animator_settings = {'interval': 50, 'blit': True} animator_settings.update(kwargs.get('animator_settings', {})) animation = matplotlib.animation.FuncAnimation(fig, update_fig, frames=range(start_index, stop_index), **animator_settings) return animation
def animate(self, act_fn, nsteps, file_name, rate=1.5, verbose=False): """ Save an animation to an mp4 file. """ plt.figure(0) # run sim loop o = self.reset() file_path = "/".join(file_name.split("/")[0:-1]) temp_name = join(file_path, "temp_0.png") # generate .pngs self.save_image(temp_name) removed = 0 for i in range(nsteps): a = act_fn(o) o, r, done, info = self.step(a) temp_name = join(file_path, "temp_" + str(i + 1) + ".png") self.save_image(temp_name) removed += info['removed'] if verbose: print(r, info) if done: break if verbose: print("Total removed:", removed) # use ffmpeg to create .pngs to .mp4 movie ffmpeg_cmd = "ffmpeg -framerate " + str(rate) + " -i " + join( file_path, "temp_%d.png") + " -c:v libx264 -pix_fmt yuv420p " + file_name call(ffmpeg_cmd.split()) # clean-up by removing .pngs map(os.remove, glob.glob(join(file_path, "temp_*.png")))
def plot_2d_animation(input, mask, predictions): rgb_image = np.concatenate((input, input, input), axis=0) mask = np.concatenate((np.zeros_like(input), mask, predictions), axis=0) # green = targets # blue = predictions # red = overlap idxs = np.where(mask > 0.3) rgb_image[idxs] = mask[idxs] rgb_image = np.rollaxis(rgb_image, axis=0, start=4) print rgb_image.shape def get_data_step(step): return rgb_image[step, :, :, :] fig = plt.figure() im = fig.gca().imshow(get_data_step(0)) def init(): im.set_data(get_data_step(0)) return im, def animate(i): im.set_data(get_data_step(i)) return im, anim = animation.FuncAnimation(fig, animate, init_func=init, frames=rgb_image.shape[1], interval=20000 / rgb_image.shape[0], blit=True) def on_click(event): global anim_running if anim_running: anim.event_source.stop() anim_running = False else: anim.event_source.start() anim_running = True fig.canvas.mpl_connect('button_press_event', on_click) try: plt.show() except AttributeError: pass
def animation3D(agents, function, lb, ub, sr=False): side = np.linspace(lb, ub, 45) X, Y = np.meshgrid(side, side) zs = np.array([function([x, y]) for x, y in zip(np.ravel(X), np.ravel(Y))]) Z = zs.reshape(X.shape) fig = plt.figure() ax = Axes3D(fig) surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='jet', linewidth=0, antialiased=False) ax.set_xlim(lb, ub) ax.set_ylim(lb, ub) ax.zaxis.set_major_locator(LinearLocator(10)) ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f')) fig.colorbar(surf, shrink=0.5, aspect=5) iter = len(agents) n = len(agents[0]) t = np.array([np.ones(n) * i for i in range(iter)]).flatten() b = [] [[b.append(agent) for agent in epoch] for epoch in agents] c = [function(x) for x in b] a = np.asarray(b) df = pd.DataFrame({"time": t, "x": a[:, 0], "y": a[:, 1], "z": c}) def update_graph(num): data = df[df['time'] == num] graph._offsets3d = (data.x, data.y, data.z) title.set_text(function.__name__ + " " * 45 + 'iteration: {}'.format( num)) title = ax.set_title(function.__name__ + " " * 45 + 'iteration: 0') data = df[df['time'] == 0] graph = ax.scatter(data.x, data.y, data.z, color='black') ani = matplotlib.animation.FuncAnimation(fig, update_graph, iter, interval=50, blit=False) if sr: ani.save('result.mp4') plt.show()