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')
python类FuncAnimation()的实例源码
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 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