本文整理汇总了Python中matplotlib.animation.FuncAnimation类的典型用法代码示例。如果您正苦于以下问题:Python FuncAnimation类的具体用法?Python FuncAnimation怎么用?Python FuncAnimation使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了FuncAnimation类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: AnimationWidget
class AnimationWidget(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
vbox = QtGui.QVBoxLayout()
self.canvas = MyMplCanvas(self, width=5, height=4, dpi=100)
vbox.addWidget(self.canvas)
hbox = QtGui.QHBoxLayout()
self.start_button = QtGui.QPushButton("start", self)
self.stop_button = QtGui.QPushButton("stop", self)
self.start_button.clicked.connect(self.on_start)
self.stop_button.clicked.connect(self.on_stop)
hbox.addWidget(self.start_button)
hbox.addWidget(self.stop_button)
vbox.addLayout(hbox)
self.setLayout(vbox)
self.x = np.linspace(0, 5*np.pi, 400)
self.p = 0.0
self.y = np.sin(self.x + self.p)
self.line, = self.canvas.axes.plot(self.x, self.y, animated=True, lw=2)
def update_line(self, i):
self.p += 0.1
y = np.sin(self.x + self.p)
self.line.set_ydata(y)
return [self.line]
def on_start(self):
self.ani = FuncAnimation(self.canvas.figure, self.update_line,
blit=True, interval=25)
def on_stop(self):
self.ani._stop()
示例2: record_gif
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')
示例3: __init__
def __init__(self, fig, startFrame, endFrame, tail, fade=False, **kwargs) :
"""
Create an animation of track segments.
*fig* matplotlib Figure object
*startFrame* The frame number to start animation loop at
*endFrame* The frame number to end the loop at
*tail* How many frames to keep older segments in view
*fade* Whether or not to fade track tails for
non-active tracks (default: False).
All other :class:`FuncAnimation` constructor kwargs are available
except *frames* and *fargs*.
TODO: Add usage info.
"""
self._lineData = []
self._lines = []
if 'frames' in kwargs :
raise KeyError("Do not specify 'frames' for the constructor"
" of SegAnimator")
self.fade = fade
FuncAnimation.__init__(self, fig, self.update_lines,
endFrame - startFrame + 1,
fargs=(self._lineData, self._lines,
startFrame, endFrame, tail),
**kwargs)
示例4: main
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: Blocks
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)
示例6: plot_worker
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()
示例7: showAnimation
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")
示例8: run
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
示例9: main
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'])
示例10: plot_data_scatterplot
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()
示例11: confusion_worker
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()
示例12: generate
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)
示例13: animate
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)
示例14: main
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')
示例15: __init__
def __init__(self, fig, files, load_func=None, robust=False, **kwargs):
"""
Create an animation object for viewing radar reflectivities.
*fig* matplotlib Figure object
*files* list of filenames containing the radar data
*load_func* The function to use to load the data from a file.
Must return a dictionary of 'vals' which contains
the 3D numpy array (T by Y by X), 'lats' and 'lons'.
It is also optional that the loading function also
provides a 'scan_time', either as a
:class:`datetime.datetime` object or as an integer
or a float representing the number of seconds since
UNIX Epoch.
*frames* The number of frames to display. If not given, then
assume it is the same number as 'len(files)'.
*robust* Boolean (default: False) indicating whether or not
we can assume all the data will be for the same domain.
If you can't assume a consistant domain, then set
*robust* to True. This often happens for PAR data.
Note that a robust rendering is slower.
All other kwargs for :class:`FuncAnimation` are also allowed.
To use, specify the axes to display the image on using :meth:`add_axes`.
"""
self._rd = files
self._loadfunc = load_func if load_func is not None else LoadRastRadar
self._ims = []
self._im_kwargs = []
self._new_axes = []
self._curr_time = None
self._robust = robust
frames = kwargs.pop("frames", None)
# if len(files) < frames :
# raise ValueError("Not enough data files for the number of frames")
FuncAnimation.__init__(
self,
fig,
self.nextframe,
frames=len(self._rd),
# init_func=self.firstframe,
**kwargs
)