本文整理汇总了Python中matplotlib.animation.FuncAnimation.save方法的典型用法代码示例。如果您正苦于以下问题:Python FuncAnimation.save方法的具体用法?Python FuncAnimation.save怎么用?Python FuncAnimation.save使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.animation.FuncAnimation
的用法示例。
在下文中一共展示了FuncAnimation.save方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: confusion_worker
# 需要导入模块: from matplotlib.animation import FuncAnimation [as 别名]
# 或者: from matplotlib.animation.FuncAnimation import save [as 别名]
def confusion_worker(queue, animation=False):
"""Matplotlib worker."""
config = get_config()
titles = json.loads(config.get('sentiment', 'titles'))
def init():
clear_annotations(annotations)
for ax, image, title in zip(axes, images, titles):
empty_confusion = [[0] * 3] * 3
image.set_data(empty_confusion)
# annotate_confusion_matrix(ax, empty_confusion, annotations)
return images
fig, axes, images, annotations = make_confusion()
# Important to assign it to a variable, even if we don't use it.
anim = FuncAnimation(fig=fig,
func=update_confusion,
frames=lambda: get_data(queue),
fargs=(images, axes, annotations),
interval=200,
repeat=False,
init_func=init,
blit=False)
if animation:
anim.save('confusion.mp4', fps=10, extra_args=['-vcodec', 'libx264'])
else:
plt.show()
示例2: main
# 需要导入模块: from matplotlib.animation import FuncAnimation [as 别名]
# 或者: from matplotlib.animation.FuncAnimation import save [as 别名]
def main(self, outfile, fps=30):
frame = defaultdict(list)
for _, [t, item], val in self.interp.chart['frame/2'][:,:,:]:
if val:
frame[t].append(item)
nframes = max(frame)
def draw_frame(t):
ax.cla()
ax.set_title(t)
ax.set_xlim(-2,2) # TODO: this isn't right...
ax.set_ylim(-2,2)
if t not in frame:
print 'frame', t, 'missing.'
for item in frame[t]:
if item.fn == 'line/2':
[(a,b), (c,d)] = map(topython, item.args)
ax.plot([a,c], [b,d], color='b', alpha=0.5)
elif item.fn == 'text/2':
(s,(x,y)) = map(topython, item.args)
ax.text(x,y,s)
else:
print 'dont know how to render', item
fig = pl.figure()
ax = pl.axes()
anim = FuncAnimation(fig, draw_frame, frames=nframes)
anim.save(outfile, fps=fps, extra_args=['-vcodec', 'libx264'])
示例3: plot_worker
# 需要导入模块: from matplotlib.animation import FuncAnimation [as 别名]
# 或者: from matplotlib.animation.FuncAnimation import save [as 别名]
def plot_worker(queue, animation=False):
"""Matplotlib worker."""
def init():
updated_lines = []
for ax_lines in lines:
for line, x, y in ax_lines:
line.set_data([], [])
updated_lines.append(line)
return updated_lines
fig, axes, lines = make_subplots()
# Important to assign it to a variable, even if we don't use it.
anim = FuncAnimation(fig=fig,
func=update_figure,
frames=lambda: get_data(queue),
fargs=(lines, axes),
interval=200,
repeat=False,
init_func=init,
blit=False)
if animation:
anim.save('plot.mp4', fps=10, extra_args=['-vcodec', 'libx264'])
else:
plt.show()
示例4: main
# 需要导入模块: from matplotlib.animation import FuncAnimation [as 别名]
# 或者: from matplotlib.animation.FuncAnimation import save [as 别名]
def main():
fig = plt.figure(figsize=(3.2, 1.8))
ax = fig.add_axes([0, 0, 1, 1])
signal = create_gammapy_skymap().data
background = np.ones(signal.shape)
background /= background.sum()
data = (1 * signal + background) / 2.
# setup counts generator
pdf = data.copy().flatten()
x = np.arange(pdf.size)
counts_generator = rv_discrete(name='counts', values=(x, pdf))
counts = np.zeros_like(data)
image = ax.imshow(counts, cmap='afmhot', origin='lower', vmin=0, vmax=9,
interpolation='None')
bins = np.arange(counts.size + 1) - 0.5
anim = FuncAnimation(fig, animate, fargs=[image, counts, bins, counts_generator],
frames=200, interval=50)
filename = 'gammapy_logo.gif'
anim.save(filename, writer='imagemagick')
示例5: record_gif
# 需要导入模块: from matplotlib.animation import FuncAnimation [as 别名]
# 或者: from matplotlib.animation.FuncAnimation import save [as 别名]
def record_gif(self, gen_func, savefn):
gen = gen_func()
frame_func = lambda t: next(gen)
ax = plt.subplot(1,1,1)
f = ax.get_figure()
animation = FuncAnimation(f, frame_func, frames = np.arange(0,10,0.1), interval = 200)
animation.save(savefn + '.gif', dpi = 80, writer = 'imagemagick')
示例6: Blocks
# 需要导入模块: from matplotlib.animation import FuncAnimation [as 别名]
# 或者: from matplotlib.animation.FuncAnimation import save [as 别名]
class Blocks():
def __init__(self, numBlocks,L,data, point_count,colormap):
self.point_count = point_count
self.data = data
self.c = data-data[0]
self.positions = np.linspace(0,L,numBlocks)
self.get_color_range(colormap, self.c)
self.fig,self.ax = plt.subplots()
self.scatter = plt.scatter(self.data[0],np.zeros_like(self.data[0]),
c=self.crange[0],s=50,
cmap = colormap)
self.animation = FuncAnimation(self.fig, self.update,data.shape[0],
fargs=(self.data, self.scatter),
interval =25)
def get_color_range(self,colormap, c):
mapper = cm.ScalarMappable(cmap = colormap)
self.crange = mapper.to_rgba(c)
def update(self,num,data, scat):
array = np.array((data[num],np.zeros_like(data[num]))).T
self.scatter.set_offsets(array)
self.scatter.set_facecolor(self.crange[num]),
print ("%d/%d" %(num,self.point_count))
return self.scatter,
def animate(self, numBlocks, save = False, filename="output/animation.gif"):
plt.show()
if save:
print("Writing to %s, this make take a while" %filename)
self.animation.save(filename, writer='imagemagick', fps=30)
示例7: run
# 需要导入模块: from matplotlib.animation import FuncAnimation [as 别名]
# 或者: from matplotlib.animation.FuncAnimation import save [as 别名]
def run(self, animating = False, iteration_count = 10000):
population_counts = np.zeros((2, iteration_count), dtype=int)
def loop(t):
if animating:
self.draw()
self.step()
for agent in self.agents:
if agent.type == PREDATOR:
population_counts[0,t] += 1
else:
population_counts[1,t] += 1
if animating:
figure = plt.figure()
figure.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=None, hspace=None)
animation = FuncAnimation(figure, loop, init_func=self.init_drawing,
frames=iteration_count)
# save video
directory = "videos"
if not os.path.exists(directory):
os.makedirs(directory)
filename = "{}/{}.mp4".format(directory, datetime.now())
animation.save(filename, fps=20, codec="libx264", extra_args=['-pix_fmt','yuv420p'])
else:
animation = None
for t in range(iteration_count):
loop(t)
if np.any(population_counts[:,t] == 0):
return population_counts[:, :t + 1]
return population_counts
示例8: plot_data_scatterplot
# 需要导入模块: from matplotlib.animation import FuncAnimation [as 别名]
# 或者: from matplotlib.animation.FuncAnimation import save [as 别名]
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()
示例9: showAnimation
# 需要导入模块: from matplotlib.animation import FuncAnimation [as 别名]
# 或者: from matplotlib.animation.FuncAnimation import save [as 别名]
def showAnimation(self, Nframe=500):
ax = self.fig.add_axes([0,0,1,1])
plt.cla()
color_map = {1:'b', 2:'r', 3:'g'}
animation = FuncAnimation(self.fig, self.updateFig, interval=50, blit=False, frames=Nframe)
animation.save("LanguageAdoptionModel.mp4")
示例10: animate
# 需要导入模块: from matplotlib.animation import FuncAnimation [as 别名]
# 或者: from matplotlib.animation.FuncAnimation import save [as 别名]
def animate(basetimer,fig,timer=None,save=None,**ka):
ka['repeat'] = ka['repeat_delay']>0
from matplotlib.animation import FuncAnimation
anim = FuncAnimation(fig,save_count=1,**ka)
if timer is not None:
config(basetimer,**timer)
basetimer.launch(anim)
if save is not None: anim.save(**save)
示例11: generate
# 需要导入模块: from matplotlib.animation import FuncAnimation [as 别名]
# 或者: from matplotlib.animation.FuncAnimation import save [as 别名]
def generate(self, run_data):
self._print_generating_line()
self.fig = plt.figure()
self.initial(run_data)
anim = FuncAnimation(self._fig, self.animate, frames=len(self._times),
interval=run_data.log_interval_ticks)
anim.save(self.get_figfilename(), dpi=self.dpi)
plt.close(self.fig)
示例12: main
# 需要导入模块: from matplotlib.animation import FuncAnimation [as 别名]
# 或者: from matplotlib.animation.FuncAnimation import save [as 别名]
def main(data,outmov):
#entropy calculation with plots
fun = lik.VESPA_fit(data,spec_lib='bc03')
SSP = fun.SSP
ages = fun._age_unq
metal = nu.linspace(fun._metal_unq.min(),fun._metal_unq.max(),10)
t,z = nu.meshgrid(ages,metal)
spec = []
d = nu.vstack((t.ravel(),z.ravel())).T
for i in d:
try:
spec.append(SSP.get_sed(10**(i[0]-9),10**i[1]))
except:
spec.append(SSP.get_sed(round(10**(i[0]-9)),10**i[1]))
#make array
spec = nu.asarray(spec)
#match wavelenth with data
if not nu.all(nu.sort(SSP.sed_ls) == SSP.sed_ls):
#check if sorted
wave = SSP.sed_ls[::-1]
spec = spec[:,::-1]
else:
wave = SSP.sed_ls
new_spec = nu.zeros((len(d),len(data)))
for i in xrange(len(d)):
new_spec[i,:] = nu.interp(data[:,0],wave,spec[i,:])
spec = new_spec
H = get_information(data,spec)
#make animation of how information changes likelihood
#get spectra
chi = []
flux = data[:,1]
#how i think the enropy should look -sum((1-p)*log(p))
#tot_infor = nu.sum(mod_shannon(H))
#H = mod_shannon(H)
H = shannon(H)
wave =data[:,0]
del_index = flux == flux
print 'Making images'
for i in xrange(len(wave)):
index = nu.nanargmin(H)
H[index] = nu.nan
del_index[index] = False
chi.append([make_chi(flux[del_index],spec,t,z,del_index),nu.nansum(H),nu.copy(del_index)])
pik.dump((chi,z,t,wave,flux),open('temp.pik','w'),2)
print 'Saving animations as movie'
#make animation
an = anim(t, z, chi, wave, flux)
ani = FuncAnimation(an.fig,an.make_im,frames = len(chi))
ani.save(outmov+'.mp4')
示例13: anim
# 需要导入模块: from matplotlib.animation import FuncAnimation [as 别名]
# 或者: from matplotlib.animation.FuncAnimation import save [as 别名]
def anim():
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.set_xlim3d([-20.0, 20.0])
ax.set_xlabel('X')
ax.set_ylim3d([-20.0, 20.0])
ax.set_ylabel('Y')
ax.set_zlim3d([-20.0, 20.0])
ax.set_zlabel('Z')
ax.set_title('3D Test')
sc = [ax.scatter(points[0][i][0], points[0][i][1], points[0][i][2], c='b', s=0.1,facecolor='0.5', lw = 0) for i in range(len(points[0]))]
ani = FuncAnimation(fig, update, frames=3000,
fargs=(points, sc, ax), interval=10)
ani.save("basic_animation.mp4", fps=30, extra_args=['-vcodec', 'libx264'])
示例14: animate
# 需要导入模块: from matplotlib.animation import FuncAnimation [as 别名]
# 或者: from matplotlib.animation.FuncAnimation import save [as 别名]
def animate(data, arrowscale=1, savepath=None):
""" animates the quiver plot for the dataset (multiple frames)
Input:
data : xarray PIV type of DataSet
arrowscale : [optional] integer, default is 1
savepath : [optional] path to save the MP4 animation, default is None
Output:
if savepath is None, then only an image display of the animation
if savepath is an existing path, a file named im.mp4 is saved
"""
X, Y = data.x, data.y
U, V = data.u[:,:,0], data.v[:,:,0] # first frame
fig, ax = plt.subplots(1,1)
M = np.sqrt(U**2 + V**2)
Q = ax.quiver(X[::3,::3], Y[::3,::3],
U[::3,::3], V[::3,::3], M[::3,::3],
units='inches', scale=arrowscale)
cb = plt.colorbar(Q)
units = data.attrs['units']
cb.ax.set_ylabel('velocity (' + units[2] + ')')
text = ax.text(0.2,1.05, '1/'+str(len(data.t)), ha='center', va='center',
transform=ax.transAxes)
def update_quiver(num,Q,data,text):
U,V = data.u[:,:,num],data.v[:,:,num]
M = np.sqrt(U[::3,::3]**2 + V[::3,::3]**2)
Q.set_UVC(U,V,M)
text.set_text(str(num+1)+'/'+str(len(data.t)))
return Q
anim = FuncAnimation(fig, update_quiver, fargs=(Q,data,text),
frames = len(data.t), blit=False)
mywriter = FFMpegWriter()
if savepath:
p = os.getcwd()
os.chdir(savepath)
anim.save('im.mp4', writer=mywriter)
os.chdir(p)
else: anim.save('im.mp4', writer=mywriter)
示例15: __init__
# 需要导入模块: from matplotlib.animation import FuncAnimation [as 别名]
# 或者: from matplotlib.animation.FuncAnimation import save [as 别名]
def __init__(self):
N = 200
self.dx = 1. / N
cfl = .1
self.c = 100.
self.dt = cfl * self.dx / self.c
self.t = 0
self.x = np.linspace(0, 1, N)
self.u = np.sin(2 * np.pi * self.x) * 0
self.u[0] = 1
self.fig = plt.figure()
self.line, = plt.plot(self.x, self.u)
ani = FuncAnimation(self.fig, self.update, range(10000), interval=10, blit=True)
Writer = writers['ffmpeg']
writer = Writer(fps=100, metadata=dict(artist='Laurent Garcin'), bitrate=18000)
ani.save('transport.mp4', writer=writer)
plt.show()