• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python pyplot.get_fignums函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中matplotlib.pyplot.get_fignums函数的典型用法代码示例。如果您正苦于以下问题:Python get_fignums函数的具体用法?Python get_fignums怎么用?Python get_fignums使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了get_fignums函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: _setup

def _setup():
    # The baseline images are created in this locale, so we should use
    # it during all of the tests.
    try:
        locale.setlocale(locale.LC_ALL, str('en_US.UTF-8'))
    except locale.Error:
        try:
            locale.setlocale(locale.LC_ALL, str('English_United States.1252'))
        except locale.Error:
            warnings.warn(
                "Could not set locale to English/United States. "
                "Some date-related tests may fail")

    plt.switch_backend('Agg')  # use Agg backend for these test
    if mpl.get_backend().lower() != "agg":
        msg = ("Using a wrong matplotlib backend ({0}), "
               "which will not produce proper images")
        raise Exception(msg.format(mpl.get_backend()))

    # These settings *must* be hardcoded for running the comparison
    # tests
    mpl.rcdefaults()  # Start with all defaults
    mpl.rcParams['text.hinting'] = True
    mpl.rcParams['text.antialiased'] = True
    mpl.rcParams['text.hinting_factor'] = 8

    # make sure we don't carry over bad plots from former tests
    msg = ("no of open figs: {} -> find the last test with ' "
           "python tests.py -v' and add a '@cleanup' decorator.")
    assert len(plt.get_fignums()) == 0, msg.format(plt.get_fignums())
开发者ID:jwhendy,项目名称:plotnine,代码行数:30,代码来源:conftest.py


示例2: test_plot_tfr_topo

def test_plot_tfr_topo():
    """Test plotting of TFR data."""
    import matplotlib.pyplot as plt

    epochs = _get_epochs()
    n_freqs = 3
    nave = 1
    data = np.random.RandomState(0).randn(len(epochs.ch_names),
                                          n_freqs, len(epochs.times))
    tfr = AverageTFR(epochs.info, data, epochs.times, np.arange(n_freqs), nave)
    plt.close('all')
    fig = tfr.plot_topo(baseline=(None, 0), mode='ratio',
                        title='Average power', vmin=0., vmax=14.)

    # test opening tfr by clicking
    num_figures_before = len(plt.get_fignums())
    # could use np.reshape(fig.axes[-1].images[0].get_extent(), (2, 2)).mean(1)
    with pytest.warns(None):  # on old mpl there is a warning
        _fake_click(fig, fig.axes[0], (0.08, 0.65))
    assert num_figures_before + 1 == len(plt.get_fignums())
    plt.close('all')

    tfr.plot([4], baseline=(None, 0), mode='ratio', show=False, title='foo')
    pytest.raises(ValueError, tfr.plot, [4], yscale='lin', show=False)

    # nonuniform freqs
    freqs = np.logspace(*np.log10([3, 10]), num=3)
    tfr = AverageTFR(epochs.info, data, epochs.times, freqs, nave)
    fig = tfr.plot([4], baseline=(None, 0), mode='mean', vmax=14., show=False)
    assert fig.axes[0].get_yaxis().get_scale() == 'log'

    # one timesample
    tfr = AverageTFR(epochs.info, data[:, :, [0]], epochs.times[[1]],
                     freqs, nave)
    with pytest.warns(None):  # matplotlib equal left/right
        tfr.plot([4], baseline=None, vmax=14., show=False, yscale='linear')

    # one frequency bin, log scale required: as it doesn't make sense
    # to plot log scale for one value, we test whether yscale is set to linear
    vmin, vmax = 0., 2.
    fig, ax = plt.subplots()
    tmin, tmax = epochs.times[0], epochs.times[-1]
    with pytest.warns(RuntimeWarning, match='not masking'):
        _imshow_tfr(ax, 3, tmin, tmax, vmin, vmax, None, tfr=data[:, [0], :],
                    freq=freqs[[-1]], x_label=None, y_label=None,
                    colorbar=False, cmap=('RdBu_r', True), yscale='log')
    fig = plt.gcf()
    assert fig.axes[0].get_yaxis().get_scale() == 'linear'

    # ValueError when freq[0] == 0 and yscale == 'log'
    these_freqs = freqs[:3].copy()
    these_freqs[0] = 0
    with pytest.warns(RuntimeWarning, match='not masking'):
        pytest.raises(ValueError, _imshow_tfr, ax, 3, tmin, tmax, vmin, vmax,
                      None, tfr=data[:, :3, :], freq=these_freqs, x_label=None,
                      y_label=None, colorbar=False, cmap=('RdBu_r', True),
                      yscale='log')
开发者ID:SherazKhan,项目名称:mne-python,代码行数:57,代码来源:test_topo.py


示例3: decorated

 def decorated():
     # make sure we don't carry over bad images from former tests.
     assert len(plt.get_fignums()) == 0, "no of open figs: %s -> find the last test with ' " \
                                 "python tests.py -v' and add a '@cleanup' decorator." % \
                                 str(plt.get_fignums())
     func()
     assert len(plt.get_fignums()) == len(baseline_images), "different number of " \
                                                            "baseline_images and actuall " \
                                                            "plots."
     for fignum, baseline in zip(plt.get_fignums(), baseline_images):
         figure = plt.figure(fignum)
         _assert_same_figure_images(figure, baseline, _file, tol=tol)
开发者ID:bwillers,项目名称:ggplot,代码行数:12,代码来源:__init__.py


示例4: load

 def load(self):
     inter = mp.isinteractive()
     if inter: mp.ioff()
     fig_list = mp.get_fignums()
     if self.file != None:
         with open(self.file, 'r') as f:
             ps = pkl.load(f)
         self.dict = ps.dict
     for p in mp.get_fignums():
         if p not in fig_list:
             mp.close(p)
     if inter: mp.ion()
开发者ID:MStolpovskiy,项目名称:PlotStore,代码行数:12,代码来源:plotstore.py


示例5: test_plot_topomap_interactive

def test_plot_topomap_interactive():
    """Test interactive topomap projection plotting."""
    import matplotlib.pyplot as plt
    from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
    from matplotlib.figure import Figure
    evoked = read_evokeds(evoked_fname, baseline=(None, 0))[0]
    evoked.pick_types(meg='mag')
    evoked.info['projs'] = []
    assert not evoked.proj
    evoked.add_proj(compute_proj_evoked(evoked, n_mag=1))

    plt.close('all')
    fig = Figure()
    canvas = FigureCanvas(fig)
    ax = fig.gca()

    kwargs = dict(vmin=-240, vmax=240, times=[0.1], colorbar=False, axes=ax,
                  res=8, time_unit='s')
    evoked.copy().plot_topomap(proj=False, **kwargs)
    canvas.draw()
    image_noproj = np.frombuffer(canvas.tostring_rgb(), dtype='uint8')
    assert len(plt.get_fignums()) == 1

    ax.clear()
    evoked.copy().plot_topomap(proj=True, **kwargs)
    canvas.draw()
    image_proj = np.frombuffer(canvas.tostring_rgb(), dtype='uint8')
    assert not np.array_equal(image_noproj, image_proj)
    assert len(plt.get_fignums()) == 1

    ax.clear()
    evoked.copy().plot_topomap(proj='interactive', **kwargs)
    canvas.draw()
    image_interactive = np.frombuffer(canvas.tostring_rgb(), dtype='uint8')
    assert_array_equal(image_noproj, image_interactive)
    assert not np.array_equal(image_proj, image_interactive)
    assert len(plt.get_fignums()) == 2

    proj_fig = plt.figure(plt.get_fignums()[-1])
    _fake_click(proj_fig, proj_fig.axes[0], [0.5, 0.5], xform='data')
    canvas.draw()
    image_interactive_click = np.frombuffer(
        canvas.tostring_rgb(), dtype='uint8')
    assert_array_equal(image_proj, image_interactive_click)
    assert not np.array_equal(image_noproj, image_interactive_click)

    _fake_click(proj_fig, proj_fig.axes[0], [0.5, 0.5], xform='data')
    canvas.draw()
    image_interactive_click = np.frombuffer(
        canvas.tostring_rgb(), dtype='uint8')
    assert_array_equal(image_noproj, image_interactive_click)
    assert not np.array_equal(image_proj, image_interactive_click)
开发者ID:SherazKhan,项目名称:mne-python,代码行数:52,代码来源:test_topomap.py


示例6: test_plotting

    def test_plotting(self):
        Options.multiprocessing=False
        self.fldr.figure(figsize=(9,6))
        self.fldr.each.plot()
        self.assertEqual(len(plt.get_fignums()),1,"Plotting to a single figure in PlotFolder failed.")
        plt.close("all")
        self.fldr.plot(extra=extra)
        self.assertEqual(len(plt.get_fignums()),2,"Plotting to a single figure in PlotFolder failed.")
        self.ax=self.fldr[0].subplots
        self.assertEqual(len(self.ax),12,"Subplots check failed.")

        plt.close("all")
        Options.multiprocessing=True
开发者ID:gb119,项目名称:Stoner-PythonCode,代码行数:13,代码来源:test_mixins.py


示例7: _image_comparison

def _image_comparison(baseline_images, extensions=["pdf", "svg", "png"], tol=11, rtol=1e-3, **kwargs):

    for num, base in zip(plt.get_fignums(), baseline_images):
        for ext in extensions:
            fig = plt.figure(num)
            fig.canvas.draw()
            # fig.axes[0].set_axis_off()
            # fig.set_frameon(False)
            if ext in ["npz"]:
                figdict = flatten_axis(fig)
                np.savez_compressed(os.path.join(result_dir, "{}.{}".format(base, ext)), **figdict)
                fig.savefig(
                    os.path.join(result_dir, "{}.{}".format(base, "png")),
                    transparent=True,
                    edgecolor="none",
                    facecolor="none",
                    # bbox='tight'
                )
    for num, base in zip(plt.get_fignums(), baseline_images):
        for ext in extensions:
            # plt.close(num)
            actual = os.path.join(result_dir, "{}.{}".format(base, ext))
            expected = os.path.join(baseline_dir, "{}.{}".format(base, ext))
            if ext == "npz":

                def do_test():
                    if not os.path.exists(expected):
                        import shutil

                        shutil.copy2(actual, expected)
                        # shutil.copy2(os.path.join(result_dir, "{}.{}".format(base, 'png')), os.path.join(baseline_dir, "{}.{}".format(base, 'png')))
                        raise IOError("Baseline file {} not found, copying result {}".format(expected, actual))
                    else:
                        exp_dict = dict(np.load(expected).items())
                        act_dict = dict(np.load(actual).items())
                        for name in act_dict:
                            if name in exp_dict:
                                try:
                                    np.testing.assert_allclose(
                                        exp_dict[name],
                                        act_dict[name],
                                        err_msg="Mismatch in {}.{}".format(base, name),
                                        rtol=rtol,
                                        **kwargs
                                    )
                                except AssertionError as e:
                                    raise SkipTest(e)

            yield do_test
    plt.close("all")
开发者ID:mzwiessele,项目名称:topslam,代码行数:50,代码来源:test_plotting.py


示例8: test_plot_topo_image_epochs

def test_plot_topo_image_epochs():
    """Test plotting of epochs image topography."""
    title = 'ERF images - MNE sample data'
    epochs = _get_epochs()
    epochs.load_data()
    cmap = mne_analyze_colormap(format='matplotlib')
    data_min = epochs._data.min()
    plt.close('all')
    fig = plot_topo_image_epochs(epochs, sigma=0.5, vmin=-200, vmax=200,
                                 colorbar=True, title=title, cmap=cmap)
    assert epochs._data.min() == data_min
    num_figures_before = len(plt.get_fignums())
    _fake_click(fig, fig.axes[0], (0.08, 0.64))
    assert num_figures_before + 1 == len(plt.get_fignums())
    plt.close('all')
开发者ID:kdoelling1919,项目名称:mne-python,代码行数:15,代码来源:test_topo.py


示例9: setup

 def setup(self):
     func = self.func
     plt.close('all')
     self.setup_class()
     try:
         matplotlib.style.use(self.style)
         matplotlib.testing.set_font_settings_for_testing()
         func()
         assert len(plt.get_fignums()) == len(self.baseline_images), (
             "Test generated {} images but there are {} baseline images"
             .format(len(plt.get_fignums()), len(self.baseline_images)))
     except:
         # Restore original settings before raising errors.
         self.teardown_class()
         raise
开发者ID:mspacek,项目名称:matplotlib,代码行数:15,代码来源:decorators.py


示例10: save_all

def save_all(basename,pdf=True,png=True,single_pdf=False,close=True):
    """Save all figures"""
    if not pl.get_fignums(): return
    if pdf: pp = PdfPages(basename+".pdf")
    for i in pl.get_fignums():
        fig = pl.figure(i)
        if pdf: pp.savefig(fig)
        if png:
            fig.patch.set_alpha(0.0)
            fig.savefig(basename+"-%02d.png" % i)
        if single_pdf:
            fig.savefig(basename+"-%02d.pdf" % i)

    if pdf: pp.close()
    if close: pl.close("all")
开发者ID:daritter,项目名称:OpenMPIFitter,代码行数:15,代码来源:r2mpl.py


示例11: multipage

def multipage(filename, figs=None, dpi=200):
    pp = PdfPages(filename)
    if figs is None:
        figs = [plt.figure(n) for n in plt.get_fignums()]
    for fig in figs:
        fig.savefig(pp, format='pdf')
    pp.close()
开发者ID:lijuan-su,项目名称:path-learning-decoding-of-grid-place-cells,代码行数:7,代码来源:save_figures.py


示例12: cursor

def cursor(artists_or_axes=None, **kwargs):
    """Create a :class:`Cursor` for a list of artists or axes.

    Parameters
    ----------

    artists_or_axes : Optional[List[Union[Artist, Axes]]]
        All artists in the list and all artists on any of the axes passed in
        the list are selectable by the constructed :class:`Cursor`.  Defaults
        to all artists on any of the figures that :mod:`pyplot` is tracking.

    **kwargs
        Keyword arguments are passed to the :class:`Cursor` constructor.
    """

    if artists_or_axes is None:
        artists_or_axes = [ax
                           for fig in map(plt.figure, plt.get_fignums())
                           for ax in fig.axes]
    elif not isinstance(artists_or_axes, Iterable):
        artists_or_axes = [artists_or_axes]
    artists = []
    for entry in artists_or_axes:
        if isinstance(entry, Axes):
            ax = entry
            artists.extend(ax.lines + ax.patches + ax.collections + ax.images)
            # No need to extend with each container (ax.containers): the
            # contained artists have already been added.
        else:
            artist = entry
            artists.append(artist)
    return Cursor(artists, **kwargs)
开发者ID:bbgky,项目名称:mplcursors,代码行数:32,代码来源:_mplcursors.py


示例13: test_hist_by_no_extra_plots

 def test_hist_by_no_extra_plots(self):
     import matplotlib.pyplot as plt
     n = 10
     df = DataFrame({'gender': tm.choice(['Male', 'Female'], size=n),
                     'height': random.normal(66, 4, size=n)})
     axes = df.height.hist(by=df.gender)
     self.assertEqual(len(plt.get_fignums()), 1)
开发者ID:FashtimeDotCom,项目名称:pandas,代码行数:7,代码来源:test_graphics.py


示例14: show_pdf

def show_pdf(filename,width=0.5,aspect=None):
    """
    Displays the specified pdf file in a ipython/jupiter notebook.
    The width is given as screen width, the height is given via the
    aspect ratio.
    
    Arguments:
    ----------
    
    filename : string
        The path of the pdf to be shown
       
    Keywords:
    ---------
    
    width : float
        The width where 1 = full width
        
    aspect : float
        The aspect ratio width/height. Defaults to last figure's
        aspect ratio or to 4./3. if no figure present.
        
    Returns:
    --------
    A HTML object
    """
    if aspect is None:
        if plt.get_fignums()==[]:
            aspect = aspect or 4./3.
        else:
            aspect = plt.gcf().get_size_inches()
            aspect = aspect[0]/aspect[1]
    return HTML('<div style="position:relative;width:{:g}%;height:0;padding-bottom:{:g}%">'.format(width*100,width*100/aspect+2)+\
         '<iframe src="'+filename+'" style="width:100%;height:100%"></iframe></div>')
开发者ID:birnstiel,项目名称:Birnstiel2015_scripts,代码行数:34,代码来源:aux_functions.py


示例15: _init_figure

    def _init_figure(self, **kwargs):
        from matplotlib import pyplot

        # add new attributes
        self.colorbars = []
        self._coloraxes = []

        # create Figure
        num = kwargs.pop('num', max(pyplot.get_fignums() or {0}) + 1)
        self._parse_subplotpars(kwargs)
        super(Plot, self).__init__(**kwargs)
        self.number = num

        # add interactivity (scraped from pyplot.figure())
        backend_mod = get_backend_mod()
        try:
            manager = backend_mod.new_figure_manager_given_figure(num, self)
        except AttributeError:
            upstream_mod = importlib.import_module(
                pyplot.new_figure_manager.__module__)
            canvas = upstream_mod.FigureCanvasBase(self)
            manager = upstream_mod.FigureManagerBase(canvas, 1)
        manager._cidgcf = manager.canvas.mpl_connect(
            'button_press_event',
            lambda ev: _pylab_helpers.Gcf.set_active(manager))
        _pylab_helpers.Gcf.set_active(manager)
        pyplot.draw_if_interactive()
开发者ID:diegobersanetti,项目名称:gwpy,代码行数:27,代码来源:plot.py


示例16: process_statspecs

def process_statspecs(directive, part=None, designname=None):
    """
    Main processor for the staplestatter directive. Responsible for:
    1) Initialize figure and optionally axes as specified by the directive instructions.
    2) Loop over all statspecs and call process_statspec.
    3) Aggregate and return a list of stats/scores.
    """
    if part is None:
        part = cadnano_api.p()
    if designname is None:
        designname = os.path.splitext(os.path.basename(part.document().controller().filename()))[0]
    print("designname:", designname)

    statspecs = directive['statspecs']
    figspec = directive.get('figure', dict())
    if figspec.get('newfigure', False) or len(pyplot.get_fignums()) < 1:
        fig = pyplot.figure(**figspec.get('figure_kwargs', {}))
    else:
        fig = pyplot.gcf() # Will make a new figure if no figure has been created.
    # Here you can add more "figure/axes" specification logic:
    adjustfuncs = ('title', 'size_inches', 'dpi')
    for cand in adjustfuncs:
        if cand in figspec and figspec[cand]:
            getattr(fig, 'set_'+cand)(figspec[cand]) # equivalent to fig.title(figspec['title'])

    pyplot.ion()
    allscores = list()
    for _, statspec in enumerate(statspecs):
        scores = process_statspec(statspec, part=part, designname=designname, fig=fig)
        allscores.append(scores)
        if 'printspec' in statspec:
            print("Printing highest scores with: statspec['printspec']")
            get_highest_scores(scores, **statspec['printspec']) # This logic is subject to change.
    return dict(figure=fig, scores=allscores)
开发者ID:scholer,项目名称:staplestatter,代码行数:34,代码来源:staplestatter.py


示例17: save_plots

    def save_plots(self):
        if not self.args.out and not self.args.out_only:
            return

        print("saving plots")

        # get output prefix:
        prefix = self.args.out if self.args.out else self.args.out_only

        # create dir if needed or check for dir type
        if not os.path.exists(prefix):
            os.mkdir(prefix)
        elif not os.path.isdir(prefix):
            print("not a directory: {}".format(prefix))
            sys.exit(1)

        # Prepare for a single file with all plots
        p = os.path.join(prefix, "all_plots.pdf")
        pdf_pages = PdfPages(p)

        for fig in list(map(plt.figure, plt.get_fignums())):
            # Add plot to the one and only pdf
            pdf_pages.savefig(fig, transparent=True)

            # fetch and remove title from plot (used in filename instead)
            title = fig.axes[0].get_title().replace(' ', '_')
            fig.axes[0].set_title("")

            # create filename and save plot
            filename = os.path.join(prefix, title + ".pdf")
            print(filename)
            fig.savefig(filename, transparent=True, bbox_inches='tight', pad_inches=0)

        # Save the teh single file
        pdf_pages.close()
开发者ID:hundeboll,项目名称:riddler,代码行数:35,代码来源:plotlib.py


示例18: updatePlot

    def updatePlot(self, dataList):

        # plotLine.set_xdata(range(Nsamples))

        # if plot window is closed
        if 0 == len(plt.get_fignums()):
            return

        self.yDataLineOne.append(dataList[0]) # data 1 form queue
        del (self.yDataLineOne[0])
        self.pltLineOne.set_ydata(self.yDataLineOne)  # update the data

        ## for second line
        if len(dataList) == 2:
            self.yDataLineTwo.append(dataList[1]) # data 2 from queue
            del (self.yDataLineTwo[0])
            self.pltLineTwo.set_ydata(self.yDataLineTwo)

        ymin = float(min(self.yDataLineOne + self.yDataLineTwo))-1
        ymax = float(max(self.yDataLineOne + self.yDataLineTwo))+1
        plt.ylim([ymin,ymax])

        # update text on the plot
        self.TextValTemp1.set_text(round(self.yDataLineOne[-1], 2))
        self.TextValTemp2.set_text(round(self.yDataLineTwo[-1], 2))

        plt.draw()  # update the plot
        self.refreshPlot()
开发者ID:slapab,项目名称:pyrometer,代码行数:28,代码来源:demo_draw_graph.py


示例19: update_plots

def update_plots(data, figs):

    start = time.time()

    cur_figs = plt.get_fignums()
    if cur_figs:
        
        # plot verbose link states
        fignum = figs[0].number
        if fignum in cur_figs:
            plot_verbose_network_states(fignum, data)
        
        # plot all network states
        fignum = figs[1].number
        if fignum in cur_figs:
            plot_network_states(fignum, data)

        # plot lower level database vars
        fignum = figs[2].number
        if fignum in cur_figs:
            plot_db_vars(fignum, data)
            
        draw()
        plt.pause(.1)  
        
        end = time.time()

        print "Plotting time was: ", end-start, " seconds"
    else:
        time.sleep(1)
开发者ID:RabbitNick,项目名称:extrasy,代码行数:30,代码来源:network_state_plotter.py


示例20: main

def main():
  if '-a' in sys.argv:
    pr = 'all'
  else:
    pr = 'some'
  ns = int(sys.argv[-1])
  
  phase, intesity, tparams = genmultilc(nspots=ns,noisefactor=0.0)
  print 'tparams:', tparams
  print
  
  paramsets = ratchetfit((phase,intesity),ns,plsprint=pr,plsplot='-p' in sys.argv)
  pdists = [multiparamdists(fps,tparams) for fps in paramsets]
  
  print
  print 'tparams:', tparams
  print 'final param sets:'
  for i in range(len(paramsets)):
    print 'params: ', paramsets[i]
    print 'pdists: ', pdists[i]
  
  if '-p' in sys.argv:
    for i in plt.get_fignums():
      plt.figure(i)
      plt.savefig('figure%d.png' % i)
开发者ID:lmwalkowicz,项目名称:Cheetah,代码行数:25,代码来源:lcmultifit.py



注:本文中的matplotlib.pyplot.get_fignums函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python pyplot.getp函数代码示例发布时间:2022-05-27
下一篇:
Python pyplot.get_current_fig_manager函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap