本文整理汇总了Python中matplotlib.animation方法的典型用法代码示例。如果您正苦于以下问题:Python matplotlib.animation方法的具体用法?Python matplotlib.animation怎么用?Python matplotlib.animation使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib
的用法示例。
在下文中一共展示了matplotlib.animation方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: save_frames
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import animation [as 别名]
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)
示例2: test_plot_ppc_multichain
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import animation [as 别名]
def test_plot_ppc_multichain(kind, jitter, animated):
if animation and not animation.writers.is_available("ffmpeg"):
pytest.skip("matplotlib animations within ArviZ require ffmpeg")
data = from_dict(
posterior_predictive={
"x": np.random.randn(4, 100, 30),
"y_hat": np.random.randn(4, 100, 3, 10),
},
observed_data={"x": np.random.randn(30), "y": np.random.randn(3, 10)},
)
animation_kwargs = {"blit": False}
axes = plot_ppc(
data,
kind=kind,
data_pairs={"y": "y_hat"},
jitter=jitter,
animated=animated,
animation_kwargs=animation_kwargs,
random_seed=3,
)
if animated:
assert np.all(axes[0])
assert np.all(axes[1])
else:
assert np.all(axes)
示例3: _anim_rst
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import animation [as 别名]
def _anim_rst(anim, image_path, gallery_conf):
from matplotlib.animation import ImageMagickWriter
# output the thumbnail as the image, as it will just be copied
# if it's the file thumbnail
fig = anim._fig
image_path = image_path.replace('.png', '.gif')
fig_size = fig.get_size_inches()
thumb_size = gallery_conf['thumbnail_size']
use_dpi = round(
min(t_s / f_s for t_s, f_s in zip(thumb_size, fig_size)))
# FFmpeg is buggy for GIFs
if ImageMagickWriter.isAvailable():
writer = 'imagemagick'
else:
writer = None
anim.save(image_path, writer=writer, dpi=use_dpi)
html = anim._repr_html_()
if html is None: # plt.rcParams['animation.html'] == 'none'
html = anim.to_jshtml()
html = indent(html, ' ')
return _ANIMATION_RST.format(html)
示例4: pause
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import animation [as 别名]
def pause(interval):
"""
Pause for *interval* seconds.
If there is an active figure, it will be updated and displayed before the
pause, and the GUI event loop (if any) will run during the pause.
This can be used for crude animation. For more complex animation, see
:mod:`matplotlib.animation`.
Notes
-----
This function is experimental; its behavior may be changed or extended in a
future release.
"""
manager = _pylab_helpers.Gcf.get_active()
if manager is not None:
canvas = manager.canvas
if canvas.figure.stale:
canvas.draw_idle()
show(block=False)
canvas.start_event_loop(interval)
else:
time.sleep(interval)
示例5: test_plot_ppc
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import animation [as 别名]
def test_plot_ppc(models, kind, alpha, animated):
if animation and not animation.writers.is_available("ffmpeg"):
pytest.skip("matplotlib animations within ArviZ require ffmpeg")
animation_kwargs = {"blit": False}
axes = plot_ppc(
models.model_1,
kind=kind,
alpha=alpha,
animated=animated,
animation_kwargs=animation_kwargs,
random_seed=3,
)
if animated:
assert axes[0]
assert axes[1]
assert axes
示例6: create_graph
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import animation [as 别名]
def create_graph(self):
# Create the graph widget.
graphWidget = QtWidgets.QWidget()
graphWidget.setObjectName("graph")
# Style attributes of matplotlib.
matplotlib.rcParams['lines.linewidth'] = 3
matplotlib.rcParams['lines.color'] = '#2a2a2a'
matplotlib.rcParams['font.size'] = 10.
self.graphFigure = Figure(facecolor='#444952')
self.graphCanvas = FigureCanvas(self.graphFigure)
# Add graph widgets to layout for graph.
graphVerticalBox = QtWidgets.QVBoxLayout()
graphVerticalBox.addWidget(self.graphCanvas)
graphWidget.setLayout(graphVerticalBox)
# Animate the the graph with new data
if self.animated:
self.animateGraph = animation.FuncAnimation(self.graphFigure,
self.graph_draw, interval=1000)
else:
self.graph_draw()
return graphWidget
示例7: anim_to_html
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import animation [as 别名]
def anim_to_html(anim):
"""
adapted from: http://jakevdp.github.io/blog/2013/05/12/embedding-matplotlib-animations/
This function converts and animation object from matplotlib into HTML which can then
be embedded in an IPython notebook.
This requires ffmpeg to be installed in order to build the intermediate mp4 file
To get these to display automatically, you need to set animation.Animation._repr_html_ = plotlib.anim_to_html
(this is done on your behalf by PHOEBE)
"""
if not hasattr(anim, '_encoded_video'):
with NamedTemporaryFile(suffix='.mp4') as f:
anim.save(f.name, fps=20, extra_args=['-vcodec', 'libx264'])
video = open(f.name, "rb").read()
anim._encoded_video = video.encode("base64")
return VIDEO_TAG.format(anim._encoded_video)
# setup hooks for inline animations in IPython notebooks
示例8: run
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import animation [as 别名]
def run(self):
self._printLogs("Waiting for the robot to be in wake up position", "OKBLUE")
self.motion_service.wakeUp()
self.posture_service.goToPosture("StandInit", 0.1)
self.create_callbacks()
# self.startDLServer()
self._addTopic()
# graphplots
self._initialisePlot()
ani = animation.FuncAnimation(self.fig, self._animate, blit=False, interval=500 ,repeat=False)
# loop on, wait for events until manual interruption
try:
# while True:
# time.sleep(1)
# starting graph plot
plt.show() # blocking call hence no need for while(True)
except KeyboardInterrupt:
self._printLogs("Interrupted by user, shutting down", "FAIL")
self._cleanUp()
self._printLogs("Waiting for the robot to be in rest position", "FAIL")
# self.motion_service.rest()
sys.exit(0)
return
示例9: save_true_generated_frames
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import animation [as 别名]
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)
示例10: att_animation
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import animation [as 别名]
def att_animation(maps_array, mode, src, tgt, head_id):
weights = [maps[mode2id[mode]][head_id] for maps in maps_array]
fig, axes = plt.subplots(1, 2)
def weight_animate(i):
global colorbar
if colorbar:
colorbar.remove()
plt.cla()
axes[0].set_title('heatmap')
axes[0].set_yticks(np.arange(len(src)))
axes[0].set_xticks(np.arange(len(tgt)))
axes[0].set_yticklabels(src)
axes[0].set_xticklabels(tgt)
plt.setp(axes[0].get_xticklabels(), rotation=45, ha="right",
rotation_mode="anchor")
fig.suptitle('epoch {}'.format(i))
weight = weights[i].transpose(-1, -2)
heatmap = axes[0].pcolor(weight, vmin=0, vmax=1, cmap=plt.cm.Blues)
colorbar = plt.colorbar(heatmap, ax=axes[0], fraction=0.046, pad=0.04)
axes[0].set_aspect('equal')
axes[1].axis("off")
graph_att_head(src, tgt, weight, axes[1], 'graph')
ani = animation.FuncAnimation(fig, weight_animate, frames=len(weights), interval=500, repeat_delay=2000)
return ani
示例11: pause
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import animation [as 别名]
def pause(interval):
"""
Pause for *interval* seconds.
If there is an active figure it will be updated and displayed,
and the GUI event loop will run during the pause.
If there is no active figure, or if a non-interactive backend
is in use, this executes time.sleep(interval).
This can be used for crude animation. For more complex
animation, see :mod:`matplotlib.animation`.
This function is experimental; its behavior may be changed
or extended in a future release.
"""
backend = rcParams['backend']
if backend in _interactive_bk:
figManager = _pylab_helpers.Gcf.get_active()
if figManager is not None:
canvas = figManager.canvas
canvas.draw()
show(block=False)
canvas.start_event_loop(interval)
return
# No on-screen figure is active, so sleep() is all we need.
import time
time.sleep(interval)
示例12: movie
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import animation [as 别名]
def movie(im_List, out='movie.mp4', fps=10, dpi=120):
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig = plt.figure()
frame = im_List[0].imvec #read_auto(filelist[len(filelist)/2])
fov = im_List[0].psize*im_List[0].xdim
extent = fov * np.array((1,-1,-1,1)) / 2.
maxi = np.max(frame)
im = plt.imshow( np.reshape(frame,[im_List[0].xdim, im_List[0].xdim]) , cmap='hot', extent=extent) #inferno
plt.colorbar()
im.set_clim([0,maxi])
fig.set_size_inches([5,5])
plt.tight_layout()
def update_img(n):
sys.stdout.write('\rprocessing image %i of %i ...' % (n,len(im_List)) )
sys.stdout.flush()
im.set_data(np.reshape(im_List[n].imvec, [im_List[n].xdim, im_List[n].xdim]) )
return im
ani = animation.FuncAnimation(fig,update_img,len(im_List),interval=1e3/fps)
writer = animation.writers['ffmpeg'](fps=max(20, fps), bitrate=1e6)
ani.save(out,writer=writer,dpi=dpi)
示例13: __init__
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import animation [as 别名]
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)
示例14: coalescence_video
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import animation [as 别名]
def coalescence_video(self, file_str):
"""
Generate a video over the marginal window showing the coalescence map
and expected arrival times overlain on the station traces.
Parameters
----------
file_str : str
String {run_name}_{event_name}
"""
# Find index of start and end of marginal window
idx0 = np.where(self.times == self.event_mw_data["DT"].iloc[0])[0][0]
idx1 = np.where(self.times == self.event_mw_data["DT"].iloc[-1])[0][0]
Writer = animation.writers["ffmpeg"]
writer = Writer(fps=4, metadata=dict(artist="Ulvetanna"), bitrate=1800)
fig = self._coalescence_frame(idx0)
ani = animation.FuncAnimation(fig, self._video_update,
frames=np.linspace(idx0+1, idx1, 200),
blit=False, repeat=False)
subdir = "videos"
util.make_directories(self.run_path, subdir=subdir)
out_str = self.run_path / subdir / file_str
ani.save("{}_CoalescenceVideo.mp4".format(out_str),
writer=writer)
示例15: test_plot_ppc_discrete
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import animation [as 别名]
def test_plot_ppc_discrete(kind, animated):
if animation and not animation.writers.is_available("ffmpeg"):
pytest.skip("matplotlib animations within ArviZ require ffmpeg")
data = from_dict(
observed_data={"obs": np.random.randint(1, 100, 15)},
posterior_predictive={"obs": np.random.randint(1, 300, (1, 20, 15))},
)
animation_kwargs = {"blit": False}
axes = plot_ppc(data, kind=kind, animated=animated, animation_kwargs=animation_kwargs)
if animated:
assert np.all(axes[0])
assert np.all(axes[1])
assert axes