當前位置: 首頁>>代碼示例>>Python>>正文


Python matplotlib.animation方法代碼示例

本文整理匯總了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) 
開發者ID:simonkamronn,項目名稱:kvae,代碼行數:23,代碼來源:movie.py

示例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) 
開發者ID:arviz-devs,項目名稱:arviz,代碼行數:27,代碼來源:test_plots_matplotlib.py

示例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) 
開發者ID:sphinx-gallery,項目名稱:sphinx-gallery,代碼行數:23,代碼來源:scrapers.py

示例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) 
開發者ID:Relph1119,項目名稱:GraphicDesignPatternByPython,代碼行數:26,代碼來源:pyplot.py

示例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 
開發者ID:arviz-devs,項目名稱:arviz,代碼行數:18,代碼來源:test_plots_matplotlib.py

示例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 
開發者ID:Roastero,項目名稱:Openroast,代碼行數:27,代碼來源:customqtwidgets.py

示例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 
開發者ID:phoebe-project,項目名稱:phoebe2,代碼行數:23,代碼來源:mpl_animate.py

示例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 
開發者ID:maverickjoy,項目名稱:pepper-robot-programming,代碼行數:33,代碼來源:asthama_search.py

示例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) 
開發者ID:simonkamronn,項目名稱:kvae,代碼行數:38,代碼來源:movie.py

示例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 
開發者ID:dmlc,項目名稱:dgl,代碼行數:30,代碼來源:viz.py

示例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) 
開發者ID:ktraunmueller,項目名稱:Computable,代碼行數:32,代碼來源:pyplot.py

示例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) 
開發者ID:achael,項目名稱:eht-imaging,代碼行數:28,代碼來源:starwarps.py

示例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) 
開發者ID:fargonauts,項目名稱:copycat,代碼行數:11,代碼來源:status.py

示例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) 
開發者ID:QuakeMigrate,項目名稱:QuakeMigrate,代碼行數:31,代碼來源:quakeplot.py

示例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 
開發者ID:arviz-devs,項目名稱:arviz,代碼行數:16,代碼來源:test_plots_matplotlib.py


注:本文中的matplotlib.animation方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。