我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用matplotlib.animation.FuncAnimation()。
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 run(self): """ Entry point for the live plotting when started as a separate process. This starts the loop """ self.entity_name = current_process().name plogger.info("Starting new thread %s", self.entity_name) self.context = zmq.Context() self.socket = self.context.socket(zmq.SUB) self.socket.connect("tcp://localhost:%d" % self.port) topic = pickle.dumps(self.var_name, protocol=pickle.HIGHEST_PROTOCOL) self.socket.setsockopt(zmq.SUBSCRIBE, topic) plogger.info("Subscribed to topic %s on port %d", self.var_name, self.port) self.init(**self.init_kwargs) # Reference to animation required so that GC doesn't clean it up. # WILL NOT work if you remove it!!!!! # See: http://matplotlib.org/api/animation_api.html ani = animation.FuncAnimation(self.fig, self.loop, interval=100) self.plt.show()
def __init__(self, session, config, live=False): if not isinstance(session, NTStorage): raise('Session must be of type \'NTStorage\'') self.session = session self.config = config self.live = live self.f = None self.axarr = None self._setup_graph() if self.live: session.add_listener(self.update_listener) self.ani = animation.FuncAnimation(self.f, self.redraw, interval=1)
def play(self, timerange): """play an animation Strongly recommend not stepping though each timesteps; use some skips! :param timerange: range generator of time steps to animate """ import matplotlib.pyplot as plt import matplotlib.animation as animation fig = plt.figure() plt.pcolormesh(self.lat, self.axial, self.arfidata[:, :, 0]) plt.axes().set_aspect('equal') plt.gca().invert_yaxis() plt.xlabel('Lateral (mm)') plt.ylabel('Axial (mm)') anim = animation.FuncAnimation(fig, self.animate, frames=timerange, blit=False) plt.show()
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 panimate(ax, dt, pcoll, patches, boundaries, **kwargs): particles = pcoll.P coll = ellipse_collection(ax, particles) def init(): return () #ax.clear() #ax.add_patch(rect) #return (rect, ) def animate(i): if i == 0: for patch in patches: ax.add_patch(patch) ax.add_collection(coll) else: move(particles, dt, boundaries) xy = np.array([p.x[::2].flatten() for p in particles]) coll.set_offsets(xy) return tuple(patches + [coll]) kwargs = dict(dict(frames=1800, interval=10, blit=True), **kwargs) ani = animation.FuncAnimation(ax.figure, animate, init_func=init, **kwargs) return ani
def _animate_bbvi(self, stored_parameters, stored_predictive_likelihood): """ Produces animated plot of BBVI optimization Returns ---------- None (changes model attributes) """ from matplotlib.animation import FuncAnimation, writers import matplotlib.pyplot as plt import seaborn as sns fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ud = BBVINLLTAnimate(ax,self.data,stored_parameters,self.index,self.z_no,self.link) anim = FuncAnimation(fig, ud, frames=np.arange(stored_parameters.shape[0]), init_func=ud.init, interval=10, blit=True) plt.plot(self.data) plt.xlabel("Time") plt.ylabel(self.data_name) plt.show()
def _animate_bbvi(self,stored_latent_variables,stored_predictive_likelihood): """ Produces animated plot of BBVI optimization Returns ---------- None (changes model attributes) """ from matplotlib.animation import FuncAnimation, writers import matplotlib.pyplot as plt import seaborn as sns fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ud = BBVINLLMAnimate(ax,self.data,stored_latent_variables,self.index,self.z_no,self.link) anim = FuncAnimation(fig, ud, frames=np.arange(stored_latent_variables.shape[0]), init_func=ud.init, interval=10, blit=True) plt.plot(self.data) plt.xlabel("Time") plt.ylabel(self.data_name) plt.show()
def plot_animated_heatmap(windows, title, ax_props=None, more_props=None): fig, im, footer = plot_heatmap(windows[0], title, ax_props, more_props) axes = fig.get_axes() ax1, ax2 = axes redraws = [im, footer, ax1.xaxis, ax1.yaxis, ax2.xaxis, ax2.yaxis] anim = animation.FuncAnimation( fig, update_animated_heatmap, frames=windows, fargs=(more_props['name'], axes, im, footer, redraws), interval=250, blit=True, ) return anim,
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 PlotLearn(R, A, Y): intA = [BinVecToInt(j) for j in A] intY = [BinVecToInt(j) for j in Y] fig, ax = mpl.subplots(figsize=(20, 10)) ax.plot(intA, intY, label ='Orig') l, = ax.plot(intA, intY, label ='Pred') ax.legend(loc = 'upper left') #Updates the plot in ax as model learns data def UpdateF(i): R.fit(A, Y) YH = R.predict(A) S = MSE(Y, YH) intYH = [BinVecToInt(j) for j in YH] l.set_ydata(intYH) ax.set_title('Iteration: ' + str(i * 64) + ' - MSE: ' + str(S)) return l, ani = mpla.FuncAnimation(fig, UpdateF, frames = 2000, interval = 128, repeat = False) #ani.save('foo.gif') mpl.show() return ani
def anim(filename,varname,cax): template = filename+'_%03i.nc' nc0 = Dataset(template%(0),'r') # open proc 0 nc file nt = len(nc0.dimensions['t']) nc0.close() def animate(i): global kt time,z2d=read(filename,varname,kt) im.set_data(z2d) ti.set_text('%.0f '%time) kt +=5 return im,ti fig=plt.figure() ax = fig.add_subplot(111) time,z2d=read(filename,varname,0) im=ax.imshow(z2d,vmin=cax[0],vmax=cax[1]) ti=ax.text(100,-50,'%.0f '%time) print('launch the animation') global kt kt = 0 ani = animation.FuncAnimation(fig, animate,arange(nt),interval=5, blit=True) plt.show()
def animate(self, compute_step, iterations, train_data_update_freq=20, test_data_update_freq=100, one_test_at_start=True, more_tests_at_start=False, save_movie=False): def animate_step(i): if (i == iterations // train_data_update_freq): #last iteration compute_step(iterations, True, True) else: for k in range(train_data_update_freq): n = i * train_data_update_freq + k request_data_update = (n % train_data_update_freq == 0) request_test_data_update = (n % test_data_update_freq == 0) and (n > 0 or one_test_at_start) if more_tests_at_start and n < test_data_update_freq: request_test_data_update = request_data_update compute_step(n, request_test_data_update, request_data_update) # makes the UI a little more responsive plt.pause(0.001) if not self.is_paused(): return self._mpl_update_func() self._animation = animation.FuncAnimation(self._mpl_figure, animate_step, int(iterations // train_data_update_freq + 1), init_func=self._mlp_init_func, interval=16, repeat=False, blit=False) if save_movie: mywriter = animation.FFMpegWriter(fps=24, codec='libx264', extra_args=['-pix_fmt', 'yuv420p', '-profile:v', 'high', '-tune', 'animation', '-crf', '18']) self._animation.save("./tensorflowvisu_video.mp4", writer=mywriter) else: plt.show(block=True)
def realtime_plot(lines_conf, data_generator=None): fig = plt.figure() lines = [] if not isinstance(lines_conf, list): lines_conf = [lines_conf] for index, line_conf in enumerate(lines_conf): axes = fig.add_subplot(len(lines_conf), 1, index + 1) axes.axis(line_conf.axis_lim) line = axes.plot(line_conf.axes_x, line_conf.axes_y)[0] lines.append(line) def update(lines_data): if len(lines) <= 1 and not isinstance(lines_data, list): lines_data = [lines_data] for index, line in enumerate(lines): line.set_ydata(lines_data[index]) return lines ani = animation.FuncAnimation(fig, update, frames=data_generator, interval=20) plt.show()
def movie(self): # New figure with white background fig = plt.figure(figsize=(6,6), facecolor='white') # New axis over the whole figure, no frame and a 1:1 aspect ratio ax = fig.add_axes([0,0,1,1], frameon=False, aspect=1) line, = ax.plot([], [], lw=2) def init(): line.set_data([], []) return line, def animate(i): x = self.X y = self.Y[i] line.set_data(list(x), list(y)) return line, anim1=animation.FuncAnimation(fig, animate, init_func=init, frames=3000, interval=30) plt.show() return 0
def animate1D(self, fileName, numberOfFrames): "Animate a 1D nuclear wavefunction as it evolves in time" d = self.mySpace.nuclearDimensionality if d != 1: raise NuclearWavefunction.unplotableNuclearWavefunction() plottingAmplitude = np.abs(self.timePositionAmplitude) yMin = np.min(plottingAmplitude) yMax = np.max(plottingAmplitude) fig = plt.figure() ax = plt.axes(xlim=(-self.mySpace.xMax, self.mySpace.xMax), ylim = (yMin, yMax)) line, = ax.plot([], []) def init(): line.set_data([], []) return line, def animate(i): line.set_data(self.mySpace.xValues, plottingAmplitude[i]) return line, anim = animation.FuncAnimation(fig, animate, init_func=init, frames = numberOfFrames, interval=20, blit=True) anim.save(fileName, fps=20)
def animateFrequency(self, filename): "Animate a 2D nuclear wavefunction as it evolves in time" plottingAmplitude = np.abs(self.filteredNonresphasingFrequencySignals + self.filteredResphasingFrequencySignals) zMin = np.min(plottingAmplitude) zMax = np.max(plottingAmplitude) contourLevels = 100 contourSpacings = np.linspace(zMin, zMax, contourLevels) yVals = self.probeFrequencies xVals = self.pumpFrequencies fig = plt.figure() im = plt.contourf(xVals, yVals, plottingAmplitude[0], contourSpacings) ax = fig.gca() def animate(i, data, ax, fig): ax.cla() im = ax.contourf(xVals, yVals, data[i], contourSpacings) plt.title(str(i)) return im, anim = animation.FuncAnimation(fig, animate, frames = self.rawNonresphasingFrequencySignals.shape[0], interval=20, blit=True, fargs=(plottingAmplitude, ax, fig) ) anim.save(filename, fps=20)
def __init__(self, var_xarray, Nsteps, vmin, vmax, animationname): # Global definitions self.var = var_xarray self.Nsteps = Nsteps self.vmin = vmin self.vmax = vmax # Figure and axes self.fig = plt.figure() # self.ax = self.fig.axes() # Animation definitio anim = animation.FuncAnimation(self.fig, self.update, xrange(Nsteps), interval=1, blit=False) # Writer FFMpeg needed for mp4 film mywriter = animation.FFMpegWriter(bitrate=500) anim.save(animationname, writer=mywriter, fps=1, extra_args=['-vcodec', 'libx264'], dpi=300) # No init_plot needed
def animateMatrices(matrices,outputFilename = None): fig = plot.figure() # make figure im = plot.imshow(matrices[0], cmap=plot.get_cmap('bone'), vmin=0.0, vmax=1.0) # function to update figure def updatefig(j): # set the data in the axesimage object im.set_array(matrices[j]) # return the artists set return im, # kick off the animation ani = animation.FuncAnimation(fig, updatefig, frames=range(len(matrices)), interval=50, blit=True) if outputFilename != None: ani.save(outputFilename, dpi = 80,writer = 'imagemagick') plot.show()
def train(self, training_agent, total_episode, save_movie=False): def animate_func(step): #self.step = step if step > total_episode: print("Finish training ") #plt.close() else: training_agent(episode=step, visual=self) plt.pause(1.001) # makes the UI a little more responsive if not self.ispause: return self._update() self.am = animation.FuncAnimation(self._fig, animate_func, total_episode, init_func=self._init, interval=16, repeat=False, blit=False) if save_movie: mywriter = animation.FFMpegWriter(fps=24, codec='libx264', extra_args=['-pix_fmt', 'yuv420p', '-profile:v', 'high', '-tune', 'animation', '-crf', '18']) self.am.save("./video.mp4", writer=mywriter) else: plt.show(block=True)
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 plot_anim(self, movesets, **kwargs): pass # DOESNT WORK SINE THE LENGTH OF A MOVESET IS VARIABLE # setup = self.plot_moveset(movesets[0], show=False, export=True, export_plots=True, plot=True) # fig = setup['fig'] # ax = setup['ax'] # plots = setup['plots'] # # def update(i): # label = 'Generation {}'.format(i) # path, bumps = self.plot_moveset(movesets[i], export_data=True) # path_xs, path_ys = Labyrinth._transform_array_into_xy(path) # bumps_xs, bumps_ys = Labyrinth._transform_array_into_xy(bumps) # # plots[0].set_offsets(bumps_xs, bumps_ys) # # plots[1].set_offsets(path[0]) # # plots[2].set_offsets((path_xs[-1], path_ys[-1])) # for i, j in enumerate(range(len(path)-2, -1, -1), 3): # plots[i].set_positions([path_xs[i], path_ys[i]], [path_xs[i + 1], path_ys[i + 1]]) # # plots[len(plots)-1] # return plots # # mywriter = animation.FFMpegWriter() # ani = animation.FuncAnimation(fig, update, frames=np.arange(0, len(movesets)), interval=200) # ani.save('asd.mp4', writer=mywriter)
def viz(): # Prepare data X = np.arange(0, 10, 0.1) test_y = X * np.sin(X) # e = np.random.normal(0, 1, size=len(X)) # train_y = test_y + e train_y = test_y.copy() X = X[:, None] print("X's shape = %s, train_y's shape = %s, test_y's shape = %s" % (X.shape, train_y.shape, test_y.shape)) # Visualize fig, ax = plt.subplots(1, 1, sharex=True, sharey=True, figsize=[7, 7], facecolor='w') ani = animation.FuncAnimation(fig, run_boosted_regression_tree, range(25), fargs=(X, train_y, test_y, ax), blit=False, interval=1000, repeat=True) plt.show() # ani.save('BoostedRegressor.gif', writer='imagemagick')
def animate(Vh, state, same_colorbar=True, colorbar=True, subplot_loc=None, mytitle=None, show_axis='off', logscale=False): fig = plt.figure() vmin = None vmax = None if same_colorbar: vmin = 1e30 vmax = -1e30 for s in state.data: smax = s.max() smin = s.min() if smax > vmax: vmax = smax if smin < vmin: vmin = smin def my_animate(i): time_stamp = "Time: {0:f} s" obj = dl.Function(Vh, state.data[i]) t = mytitle + time_stamp.format(state.times[i]) plt.clf() return plot(obj, colorbar=True, subplot_loc=None, mytitle=t, show_axis='off', vmin=vmin, vmax=vmax, logscale=False) return animation.FuncAnimation(fig, my_animate, np.arange(0, state.nsteps), blit=True)
def __call__(self, sample): ''' For given instance, obtain data from OpenBCI and a) save to .CSV, and b) update the graph. ''' t = timeit.default_timer() - self.start_time # print timeSinceStart|Sample Id if self.verbose: print("CSV: %f | %d" % (t, sample.id)) row = '' row += str(t) row += self.delim row += str(sample.id) row += self.delim for i in sample.channel_data: row += str(i) row += self.delim for i in sample.aux_data: row += str(i) row += self.delim # remove last comma row += '\n' with open(self.file_name, 'a') as f: f.write(row) ani = animation.FuncAnimation(self.fig, animate, interval=1000) plt.show()
def visualize(self, num=100, save=False): """ Visualizes given Sorting Algorithm :param num: Number of points that has to be chosen for visualization :param save: Boolean indicating whether to save animation in 'output' directory """ plt.title(self.sorter.name + " Visualization") plt.xlabel("Array Index") plt.ylabel("Element") data = np.arange(num) ran.shuffle(data) self.sorter.sort(data, visualization=True) self.hist_arr = self.sorter.hist_array self.scatter = plt.scatter(np.arange(self.hist_arr.shape[1]), self.hist_arr[0]) # plt.scatter(x-array,y-array) self.animation = animation.FuncAnimation(self.fig, self.__update, frames=self.hist_arr.shape[0], repeat=False, blit=False, interval=1) if save: import os import errno path = "output" try: os.makedirs(path) except OSError as exc: if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise path = os.path.join('output', self.sorter.name + ".mp4") p1 = Process( target=lambda: self.animation.save(path, writer=animation.FFMpegWriter(fps=100))) p1.start() plt.show()
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 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()
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 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 video(rw, cyl=False, **aniparams): R = rw.params.R Htop = rw.params.Htop Hbot = rw.params.Hbot #fig = plt.figure() #fig.set_size_inches(6, 6) #ax = plt.axes([0,0,1,1], autoscale_on=False, xlim=(-R, R), ylim=(-H, H)) xlim = (-R, R) if not cyl else (0., R) ax = plt.axes(xlim=xlim, ylim=(-Hbot, Htop)) #streamlines(rx=R, ry=Htop, Nx=100, Ny=100, maxvalue=None, F=rw.F) coll = rw.ellipse_collection(ax) patches = rw.polygon_patches(cyl) def init(): return () def animate(t): if t == 0: ax.add_collection(coll) for p in patches: ax.add_patch(p) rw.move_ellipses(coll, cyl=cyl) return tuple([coll] + patches) aniparams = dict(dict(interval=10, blit=True, save_count=5000), **aniparams) ani = animation.FuncAnimation(ax.figure, animate, frames=rw.walk(), init_func=init, **aniparams) return ani
def point_animation(point_func, *args): global get_point_function, arguments fig1 = plt.figure() get_point_function = point_func arguments = args ani = anim.FuncAnimation(fig1, update, init_func=init, blit=True, repeat_delay=0) plt.show()
def plot_quad_3d(args=()): 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] set_limit((-0.5,0.5), (-0.5,0.5), (-0.5,5)) an = animation.FuncAnimation(fig, _callback, fargs = args, init_func=None, frames=400, interval=10, blit=False) if len(sys.argv) > 1 and sys.argv[1] == 'save': an.save('sim.gif', dpi=80, writer='imagemagick', fps=60) else: 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 animate(base_ps, init_ps, init_time, frames, plotting_args, fixed_limits=True,\ interval=100, blit=False, metawargs={}, **kwargs): ao = Animation(init_ps, init_time, fixed_limits, plotting_args, metawargs) anim = animation.FuncAnimation(ao.fig, ao, fargs=(base_ps,),\ init_func=ao.anim_init, frames=frames, interval=interval,\ blit=blit, **kwargs) return anim, ao
def plot(learning_pipeline, export): plt.ion() animated_plot = animation.FuncAnimation(figure, update_batch_graph, learning_pipeline, blit=False, interval=10, repeat=False, init_func=init) return animated_plot
def ani_frame(): dpi = 600 fig = plt.figure() ax = fig.add_subplot(111) ax.set_aspect('equal') plt.xlim(0,151); plt.ylim(0,151); ws2 = copy.deepcopy(ws); fig.set_size_inches([5,5]) plt.tight_layout() ws2.plot(ax = ax); shifts = np.linspace(0,50,100); def update_fig(n): ax.cla(); ws2 = copy.deepcopy(ws); ws2.move_forward(shifts[n]); ws2.plot(ax = ax); ax.set_xlim(0,151); ax.set_ylim(0,151); return ax #legend(loc=0) ani = animation.FuncAnimation(fig,update_fig,100,interval=30) writer = animation.writers['ffmpeg'](fps=30) ani.save('forward.mp4',writer=writer,dpi=dpi) return ani
def ani_frame(): dpi = 600 fig = plt.figure() ax = fig.add_subplot(111) ax.set_aspect('equal') plt.xlim(0,151); plt.ylim(0,151); ws2 = copy.deepcopy(ws); fig.set_size_inches([5,5]) plt.tight_layout() ws2.plot(ax = ax); shifts = np.linspace(-1,1,100); def update_fig(n): ax.cla(); ws2 = copy.deepcopy(ws); ws2.bend(shifts[n], head = True, exponent = 2); ws2.plot(ax = ax); ax.set_xlim(0,151); ax.set_ylim(0,151); return ax #legend(loc=0) ani = animation.FuncAnimation(fig,update_fig,100,interval=30) writer = animation.writers['ffmpeg'](fps=30) ani.save('bend.mp4',writer=writer,dpi=dpi) return ani
def plot(): 'Waring: Cannot stop this,once started' anim = FuncAnimation(layer.getLayer(), update, interval = 10) plt.show() #----------------------------------------------------------------------------
def _animate(fig, ax, frame_data, line_width=2, fps=10, tail_color='r', tail_alpha=0.75, head_color='b', head_alpha=1): segments, segment_frames, timestamps, fade_frames = frame_data head_color = np.array(to_rgb(head_color))[None] tail_color = np.array(to_rgb(tail_color))[None] # start with all segments transparent segment_colors = np.zeros((len(segments), 4), dtype=float) lines = LineCollection(segments, linewidths=line_width, colors=segment_colors) ax.add_collection(lines) timer = ax.text(1, 0, '0:00:00', transform=ax.transAxes, zorder=3, verticalalignment='bottom', horizontalalignment='right', bbox=dict(facecolor='white')) def update_frame(frame_idx): frame_diff = frame_idx - segment_frames mask = frame_diff < 0 # compute head alpha alpha1 = 1 - np.minimum(frame_diff/fade_frames, 1) alpha1[mask] = 0 alpha1 *= head_alpha # compute tail alpha alpha2 = (1 - mask) * tail_alpha # composite alpha and colors color, alpha = _blend_alpha(head_color, alpha1, tail_color, alpha2) segment_colors[:, :3] = color segment_colors[:, 3] = alpha lines.set_color(segment_colors) timer.set_text(timestamps[frame_idx]) return lines, timer interval = 1000. / fps return FuncAnimation(fig, update_frame, frames=len(timestamps), blit=True, interval=interval, repeat=True)
def createanim(data,start,skip,title=None,cmap='bone', ms_per_step=None): """ Return an animation of a single simulation run, each node represented (via its node label) as pixel (i,j) in an MxN image. So this will only be useful for grid graphs. Args: data: MxNxT array of voltage traces start: first timestep to show skip: timesteps to advance in each frame (higher -> faster) title: figure title cmap: matplotlib colormap (name OR object) Return: matplotlib animation object """ plt.ioff() fig = plt.figure(figsize=fig_size) titlefont = {'color' : 'black', 'size':12} ax = plt.axes()#(xlim=(0, data.shape[1]), ylim=(data.shape[0])) picture = ax.imshow(data[:, :, start], vmin=data.min(), vmax=data.max(), interpolation="nearest", cmap=cmap) plt.colorbar(picture,ax=ax,shrink=0.7) def init(): picture.set_data(data[:,:,start]) return picture def animate(i): printprogress("animating frame",start+i*skip,data.shape[2]) if i*skip < data.shape[2]: picture.set_data(data[:,:,start+i*skip]) t = " {}ms".format(start+i*skip * ms_per_step) if ms_per_step is not None else "" plt.title(title+t,titlefont) return picture anim = animation.FuncAnimation(fig, animate, init_func=init, frames=(data.shape[2]-start)/skip,interval=1, blit=False) return anim