Python matplotlib.pyplot.get_fignums() Examples

The following are code examples for showing how to use matplotlib.pyplot.get_fignums(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: decorators.py    MIT License 6 votes vote down vote up
def compare(self, idx, baseline, extension):
        __tracebackhide__ = True
        fignum = plt.get_fignums()[idx]
        fig = plt.figure(fignum)

        if self.remove_text:
            remove_ticks_and_titles(fig)

        actual_fname = (
            os.path.join(self.result_dir, baseline) + '.' + extension)
        kwargs = self.savefig_kwargs.copy()
        if extension == 'pdf':
            kwargs.setdefault('metadata',
                              {'Creator': None, 'Producer': None,
                               'CreationDate': None})
        fig.savefig(actual_fname, **kwargs)

        expected_fname = self.copy_baseline(baseline, extension)
        _raise_on_image_difference(expected_fname, actual_fname, self.tol) 
Example 2
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: __init__.py    MIT License 6 votes vote down vote up
def plot(data, kind, **kwargs):
    # Importing pyplot at the top of the file (before the converters are
    # registered) causes problems in matplotlib 2 (converters seem to not
    # work)
    import matplotlib.pyplot as plt

    if kwargs.pop("reuse_plot", False):
        ax = kwargs.get("ax")
        if ax is None and len(plt.get_fignums()) > 0:
            with plt.rc_context():
                ax = plt.gca()
            kwargs["ax"] = getattr(ax, "left_ax", ax)
    plot_obj = PLOT_CLASSES[kind](data, **kwargs)
    plot_obj.generate()
    plot_obj.draw()
    return plot_obj.result 
Example 3
Project: recruit   Author: Frank-qlu   File: _core.py    Apache License 2.0 6 votes vote down vote up
def plot_series(data, kind='line', ax=None,                    # Series unique
                figsize=None, use_index=True, title=None, grid=None,
                legend=False, style=None, logx=False, logy=False, loglog=False,
                xticks=None, yticks=None, xlim=None, ylim=None,
                rot=None, fontsize=None, colormap=None, table=False,
                yerr=None, xerr=None,
                label=None, secondary_y=False,                 # Series unique
                **kwds):

    import matplotlib.pyplot as plt
    if ax is None and len(plt.get_fignums()) > 0:
        ax = _gca()
        ax = MPLPlot._get_ax_layer(ax)
    return _plot(data, kind=kind, ax=ax,
                 figsize=figsize, use_index=use_index, title=title,
                 grid=grid, legend=legend,
                 style=style, logx=logx, logy=logy, loglog=loglog,
                 xticks=xticks, yticks=yticks, xlim=xlim, ylim=ylim,
                 rot=rot, fontsize=fontsize, colormap=colormap, table=table,
                 yerr=yerr, xerr=xerr,
                 label=label, secondary_y=secondary_y,
                 **kwds) 
Example 4
Project: FUTU_Stop_Loss   Author: BigtoC   File: _core.py    MIT License 6 votes vote down vote up
def plot_series(data, kind='line', ax=None,                    # Series unique
                figsize=None, use_index=True, title=None, grid=None,
                legend=False, style=None, logx=False, logy=False, loglog=False,
                xticks=None, yticks=None, xlim=None, ylim=None,
                rot=None, fontsize=None, colormap=None, table=False,
                yerr=None, xerr=None,
                label=None, secondary_y=False,                 # Series unique
                **kwds):

    import matplotlib.pyplot as plt
    if ax is None and len(plt.get_fignums()) > 0:
        ax = _gca()
        ax = MPLPlot._get_ax_layer(ax)
    return _plot(data, kind=kind, ax=ax,
                 figsize=figsize, use_index=use_index, title=title,
                 grid=grid, legend=legend,
                 style=style, logx=logx, logy=logy, loglog=loglog,
                 xticks=xticks, yticks=yticks, xlim=xlim, ylim=ylim,
                 rot=rot, fontsize=fontsize, colormap=colormap, table=table,
                 yerr=yerr, xerr=xerr,
                 label=label, secondary_y=secondary_y,
                 **kwds) 
Example 5
Project: PyFluxPro   Author: OzFlux   File: pfp_gfALT.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def gfalternate_done(alt_gui):
    """
    Purpose:
     Finishes up after gap filling from alternate data:
      - destroy the GapFillFromAlternate GUI
      - plot the summary statistics
      - write the summary statistics to an Excel file
    Usage:
    Side effects:
    Author: PRI
    Date: August 2014
    """
    # plot the summary statistics
    #gfalternate_plotsummary(ds,alternate_info)
    # close any open plots
    if len(plt.get_fignums()) != 0:
        for i in plt.get_fignums():
            plt.close(i)
    # destroy the alternate GUI
    alt_gui.close()
    # write Excel spreadsheet with fit statistics
    pfp_io.xl_write_AlternateStats(alt_gui.ds4, alt_gui.l4_info)
    # put the return code into ds.returncodes
    alt_gui.ds4.returncodes["message"] = "normal" 
Example 6
Project: vnpy_crypto   Author: birforce   File: _core.py    MIT License 6 votes vote down vote up
def plot_series(data, kind='line', ax=None,                    # Series unique
                figsize=None, use_index=True, title=None, grid=None,
                legend=False, style=None, logx=False, logy=False, loglog=False,
                xticks=None, yticks=None, xlim=None, ylim=None,
                rot=None, fontsize=None, colormap=None, table=False,
                yerr=None, xerr=None,
                label=None, secondary_y=False,                 # Series unique
                **kwds):

    import matplotlib.pyplot as plt
    if ax is None and len(plt.get_fignums()) > 0:
        ax = _gca()
        ax = MPLPlot._get_ax_layer(ax)
    return _plot(data, kind=kind, ax=ax,
                 figsize=figsize, use_index=use_index, title=title,
                 grid=grid, legend=legend,
                 style=style, logx=logx, logy=logy, loglog=loglog,
                 xticks=xticks, yticks=yticks, xlim=xlim, ylim=ylim,
                 rot=rot, fontsize=fontsize, colormap=colormap, table=table,
                 yerr=yerr, xerr=xerr,
                 label=label, secondary_y=secondary_y,
                 **kwds) 
Example 7
Project: ble5-nrf52-mac   Author: tomasero   File: test_figure.py    MIT License 6 votes vote down vote up
def test_figure_label():
    # pyplot figure creation, selection and closing with figure label and
    # number
    plt.close('all')
    plt.figure('today')
    plt.figure(3)
    plt.figure('tomorrow')
    plt.figure()
    plt.figure(0)
    plt.figure(1)
    plt.figure(3)
    assert plt.get_fignums() == [0, 1, 3, 4, 5]
    assert plt.get_figlabels() == ['', 'today', '', 'tomorrow', '']
    plt.close(10)
    plt.close()
    plt.close(5)
    plt.close('tomorrow')
    assert plt.get_fignums() == [0, 1]
    assert plt.get_figlabels() == ['', 'today'] 
Example 8
Project: ble5-nrf52-mac   Author: tomasero   File: decorators.py    MIT License 6 votes vote down vote up
def compare(self, idx, baseline, extension):
        __tracebackhide__ = True
        fignum = plt.get_fignums()[idx]
        fig = plt.figure(fignum)

        if self.remove_text:
            remove_ticks_and_titles(fig)

        actual_fname = (
            os.path.join(self.result_dir, baseline) + '.' + extension)
        kwargs = self.savefig_kwargs.copy()
        if extension == 'pdf':
            kwargs.setdefault('metadata',
                              {'Creator': None, 'Producer': None,
                               'CreationDate': None})
        fig.savefig(actual_fname, **kwargs)

        expected_fname = self.copy_baseline(baseline, extension)
        _raise_on_image_difference(expected_fname, actual_fname, self.tol) 
Example 9
Project: nanopores   Author: mitschabaude   File: utilities.py    MIT License 6 votes vote down vote up
def savefigs(name="fig", DIR="/tmp/", size=None, bbox_inches="tight",
             ending=".eps", **params):
    if not DIR.endswith("/"): DIR = DIR + "/"
    assertdir(DIR)
    if len(plt.get_fignums()) == 1:
        num = plt.get_fignums()[0]
        fig = plt.figure(num)
        label = fig.get_label()
        label = "" if label=="" else "_"+label
        if size is not None:
            fig.set_size_inches(size)
        fig.savefig(DIR + name + label + ending, bbox_inches=bbox_inches,
                    **params)
        return
    for num in plt.get_fignums():
        fig = plt.figure(num)
        label = fig.get_label()
        label = str(num) if label=="" else label
        if size is not None:
            fig.set_size_inches(size)
        fig.savefig(DIR + name + "_" + label + ending, bbox_inches=bbox_inches,
                    **params) 
Example 10
Project: nanopores   Author: mitschabaude   File: create_plot_traj_without_dolfin.py    MIT License 6 votes vote down vote up
def savefigs(name="fig", DIR="/tmp/", size=None, pdf=False):
    if not DIR.endswith("/"): DIR = DIR + "/"
    assertdir(DIR)
    if len(plt.get_fignums()) == 1:
        fig = plt.figure(plt.get_fignums()[0])
        if size is not None:
            fig.set_size_inches(size)
        if not pdf: suffix='.eps'
        else: suffix='.pdf'
        fig.savefig(DIR + name + suffix, bbox_inches="tight")
        return
    for num in plt.get_fignums():
        fig = plt.figure(num)
        label = fig.get_label()
        label = str(num) if label=="" else label
        if size is not None:
            fig.set_size_inches(size)
        if not pdf: suffix='.eps'
        else: suffix='.pdf'
        fig.savefig(DIR + name + "_" + label + suffix, bbox_inches="tight") 
Example 11
Project: neural-network-animation   Author: miloharper   File: test_figure.py    MIT License 6 votes vote down vote up
def test_figure_label():
    # pyplot figure creation, selection and closing with figure label and
    # number
    plt.close('all')
    plt.figure('today')
    plt.figure(3)
    plt.figure('tomorrow')
    plt.figure()
    plt.figure(0)
    plt.figure(1)
    plt.figure(3)
    assert_equal(plt.get_fignums(), [0, 1, 3, 4, 5])
    assert_equal(plt.get_figlabels(), ['', 'today', '', 'tomorrow', ''])
    plt.close(10)
    plt.close()
    plt.close(5)
    plt.close('tomorrow')
    assert_equal(plt.get_fignums(), [0, 1])
    assert_equal(plt.get_figlabels(), ['', 'today']) 
Example 12
Project: GraphicDesignPatternByPython   Author: Relph1119   File: decorators.py    MIT License 6 votes vote down vote up
def compare(self, idx, baseline, extension):
        __tracebackhide__ = True
        fignum = plt.get_fignums()[idx]
        fig = plt.figure(fignum)

        if self.remove_text:
            remove_ticks_and_titles(fig)

        actual_fname = (
            os.path.join(self.result_dir, baseline) + '.' + extension)
        kwargs = self.savefig_kwargs.copy()
        if extension == 'pdf':
            kwargs.setdefault('metadata',
                              {'Creator': None, 'Producer': None,
                               'CreationDate': None})
        fig.savefig(actual_fname, **kwargs)

        expected_fname = self.copy_baseline(baseline, extension)
        _raise_on_image_difference(expected_fname, actual_fname, self.tol) 
Example 13
Project: python3_ios   Author: holzschu   File: test_figure.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_figure_label():
    # pyplot figure creation, selection and closing with figure label and
    # number
    plt.close('all')
    plt.figure('today')
    plt.figure(3)
    plt.figure('tomorrow')
    plt.figure()
    plt.figure(0)
    plt.figure(1)
    plt.figure(3)
    assert plt.get_fignums() == [0, 1, 3, 4, 5]
    assert plt.get_figlabels() == ['', 'today', '', 'tomorrow', '']
    plt.close(10)
    plt.close()
    plt.close(5)
    plt.close('tomorrow')
    assert plt.get_fignums() == [0, 1]
    assert plt.get_figlabels() == ['', 'today'] 
Example 14
Project: predictive-maintenance-using-machine-learning   Author: awslabs   File: _core.py    Apache License 2.0 6 votes vote down vote up
def plot_series(data, kind='line', ax=None,                    # Series unique
                figsize=None, use_index=True, title=None, grid=None,
                legend=False, style=None, logx=False, logy=False, loglog=False,
                xticks=None, yticks=None, xlim=None, ylim=None,
                rot=None, fontsize=None, colormap=None, table=False,
                yerr=None, xerr=None,
                label=None, secondary_y=False,                 # Series unique
                **kwds):

    import matplotlib.pyplot as plt
    if ax is None and len(plt.get_fignums()) > 0:
        ax = _gca()
        ax = MPLPlot._get_ax_layer(ax)
    return _plot(data, kind=kind, ax=ax,
                 figsize=figsize, use_index=use_index, title=title,
                 grid=grid, legend=legend,
                 style=style, logx=logx, logy=logy, loglog=loglog,
                 xticks=xticks, yticks=yticks, xlim=xlim, ylim=ylim,
                 rot=rot, fontsize=fontsize, colormap=colormap, table=table,
                 yerr=yerr, xerr=xerr,
                 label=label, secondary_y=secondary_y,
                 **kwds) 
Example 15
Project: fund   Author: Frank-qlu   File: _core.py    Apache License 2.0 6 votes vote down vote up
def plot_series(data, kind='line', ax=None,                    # Series unique
                figsize=None, use_index=True, title=None, grid=None,
                legend=False, style=None, logx=False, logy=False, loglog=False,
                xticks=None, yticks=None, xlim=None, ylim=None,
                rot=None, fontsize=None, colormap=None, table=False,
                yerr=None, xerr=None,
                label=None, secondary_y=False,                 # Series unique
                **kwds):

    import matplotlib.pyplot as plt
    if ax is None and len(plt.get_fignums()) > 0:
        ax = _gca()
        ax = MPLPlot._get_ax_layer(ax)
    return _plot(data, kind=kind, ax=ax,
                 figsize=figsize, use_index=use_index, title=title,
                 grid=grid, legend=legend,
                 style=style, logx=logx, logy=logy, loglog=loglog,
                 xticks=xticks, yticks=yticks, xlim=xlim, ylim=ylim,
                 rot=rot, fontsize=fontsize, colormap=colormap, table=table,
                 yerr=yerr, xerr=xerr,
                 label=label, secondary_y=secondary_y,
                 **kwds) 
Example 16
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_figure.py    MIT License 6 votes vote down vote up
def test_figure_label():
    # pyplot figure creation, selection and closing with figure label and
    # number
    plt.close('all')
    plt.figure('today')
    plt.figure(3)
    plt.figure('tomorrow')
    plt.figure()
    plt.figure(0)
    plt.figure(1)
    plt.figure(3)
    assert plt.get_fignums() == [0, 1, 3, 4, 5]
    assert plt.get_figlabels() == ['', 'today', '', 'tomorrow', '']
    plt.close(10)
    plt.close()
    plt.close(5)
    plt.close('tomorrow')
    assert plt.get_fignums() == [0, 1]
    assert plt.get_figlabels() == ['', 'today'] 
Example 17
Project: psychrometric-chart-makeover   Author: buds-lab   File: decorators.py    MIT License 6 votes vote down vote up
def compare(self, idx, baseline, extension):
        __tracebackhide__ = True
        fignum = plt.get_fignums()[idx]
        fig = plt.figure(fignum)

        if self.remove_text:
            remove_ticks_and_titles(fig)

        actual_fname = (
            os.path.join(self.result_dir, baseline) + '.' + extension)
        kwargs = self.savefig_kwargs.copy()
        if extension == 'pdf':
            kwargs.setdefault('metadata',
                              {'Creator': None, 'Producer': None,
                               'CreationDate': None})
        fig.savefig(actual_fname, **kwargs)

        expected_fname = self.copy_baseline(baseline, extension)
        _raise_on_image_difference(expected_fname, actual_fname, self.tol) 
Example 18
Project: wine-ml-on-aws-lambda   Author: pierreant   File: _core.py    Apache License 2.0 6 votes vote down vote up
def plot_series(data, kind='line', ax=None,                    # Series unique
                figsize=None, use_index=True, title=None, grid=None,
                legend=False, style=None, logx=False, logy=False, loglog=False,
                xticks=None, yticks=None, xlim=None, ylim=None,
                rot=None, fontsize=None, colormap=None, table=False,
                yerr=None, xerr=None,
                label=None, secondary_y=False,                 # Series unique
                **kwds):

    import matplotlib.pyplot as plt
    if ax is None and len(plt.get_fignums()) > 0:
        ax = _gca()
        ax = MPLPlot._get_ax_layer(ax)
    return _plot(data, kind=kind, ax=ax,
                 figsize=figsize, use_index=use_index, title=title,
                 grid=grid, legend=legend,
                 style=style, logx=logx, logy=logy, loglog=loglog,
                 xticks=xticks, yticks=yticks, xlim=xlim, ylim=ylim,
                 rot=rot, fontsize=fontsize, colormap=colormap, table=table,
                 yerr=yerr, xerr=xerr,
                 label=label, secondary_y=secondary_y,
                 **kwds) 
Example 19
Project: SignLanguage_ML   Author: mareep-raljodid   File: test_figure.py    MIT License 6 votes vote down vote up
def test_figure_label():
    # pyplot figure creation, selection and closing with figure label and
    # number
    plt.close('all')
    plt.figure('today')
    plt.figure(3)
    plt.figure('tomorrow')
    plt.figure()
    plt.figure(0)
    plt.figure(1)
    plt.figure(3)
    assert plt.get_fignums() == [0, 1, 3, 4, 5]
    assert plt.get_figlabels() == ['', 'today', '', 'tomorrow', '']
    plt.close(10)
    plt.close()
    plt.close(5)
    plt.close('tomorrow')
    assert plt.get_fignums() == [0, 1]
    assert plt.get_figlabels() == ['', 'today'] 
Example 20
Project: SignLanguage_ML   Author: mareep-raljodid   File: decorators.py    MIT License 6 votes vote down vote up
def compare(self, idx, baseline, extension):
        __tracebackhide__ = True
        fignum = plt.get_fignums()[idx]
        fig = plt.figure(fignum)

        if self.remove_text:
            remove_ticks_and_titles(fig)

        actual_fname = (
            os.path.join(self.result_dir, baseline) + '.' + extension)
        kwargs = self.savefig_kwargs.copy()
        if extension == 'pdf':
            kwargs.setdefault('metadata',
                              {'Creator': None, 'Producer': None,
                               'CreationDate': None})
        fig.savefig(actual_fname, **kwargs)

        expected_fname = self.copy_baseline(baseline, extension)
        _raise_on_image_difference(expected_fname, actual_fname, self.tol) 
Example 21
Project: Blackjack-Tracker   Author: martinabeleda   File: test_figure.py    MIT License 6 votes vote down vote up
def test_figure_label():
    # pyplot figure creation, selection and closing with figure label and
    # number
    plt.close('all')
    plt.figure('today')
    plt.figure(3)
    plt.figure('tomorrow')
    plt.figure()
    plt.figure(0)
    plt.figure(1)
    plt.figure(3)
    assert plt.get_fignums() == [0, 1, 3, 4, 5]
    assert plt.get_figlabels() == ['', 'today', '', 'tomorrow', '']
    plt.close(10)
    plt.close()
    plt.close(5)
    plt.close('tomorrow')
    assert plt.get_fignums() == [0, 1]
    assert plt.get_figlabels() == ['', 'today'] 
Example 22
Project: Blackjack-Tracker   Author: martinabeleda   File: decorators.py    MIT License 6 votes vote down vote up
def compare(self, idx, baseline, extension):
        __tracebackhide__ = True
        fignum = plt.get_fignums()[idx]
        fig = plt.figure(fignum)

        if self.remove_text:
            remove_ticks_and_titles(fig)

        actual_fname = os.path.join(self.result_dir, baseline) + '.' + extension
        kwargs = self.savefig_kwargs.copy()
        if extension == 'pdf':
            kwargs.setdefault('metadata',
                              {'Creator': None, 'Producer': None,
                               'CreationDate': None})
        fig.savefig(actual_fname, **kwargs)

        expected_fname = self.copy_baseline(baseline, extension)
        _raise_on_image_difference(expected_fname, actual_fname, self.tol) 
Example 23
Project: qops   Author: lhillber   File: classical.py    MIT License 6 votes vote down vote up
def multipage(fname, figs=None, clf=True, dpi=300, clip=True, extra_artist=False):
    pp = PdfPages(fname)
    if figs is None:
        figs = [plt.figure(fignum) for fignum in plt.get_fignums()]
    for fig in figs:
        if clip is True:
            fig.savefig(
                pp, format="pdf", bbox_inches="tight", bbox_extra_artist=extra_artist
            )
        else:
            fig.savefig(pp, format="pdf", bbox_extra_artist=extra_artist)
        if clf == True:
            fig.clf()

    pp.close()


# copy/paste of network definitions
# reproduced here for convenience 
Example 24
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: decorators.py    MIT License 5 votes vote down vote up
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 
Example 25
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: testing.py    MIT License 5 votes vote down vote up
def close(fignum=None):
    from matplotlib.pyplot import get_fignums, close as _close

    if fignum is None:
        for fignum in get_fignums():
            _close(fignum)
    else:
        _close(fignum)


# -----------------------------------------------------------------------------
# contextmanager to ensure the file cleanup 
Example 26
Project: recruit   Author: Frank-qlu   File: testing.py    Apache License 2.0 5 votes vote down vote up
def close(fignum=None):
    from matplotlib.pyplot import get_fignums, close as _close

    if fignum is None:
        for fignum in get_fignums():
            _close(fignum)
    else:
        _close(fignum)


# -----------------------------------------------------------------------------
# locale utilities 
Example 27
Project: FUTU_Stop_Loss   Author: BigtoC   File: testing.py    MIT License 5 votes vote down vote up
def close(fignum=None):
    from matplotlib.pyplot import get_fignums, close as _close

    if fignum is None:
        for fignum in get_fignums():
            _close(fignum)
    else:
        _close(fignum)


# -----------------------------------------------------------------------------
# locale utilities 
Example 28
Project: vnpy_crypto   Author: birforce   File: testing.py    MIT License 5 votes vote down vote up
def close(fignum=None):
    from matplotlib.pyplot import get_fignums, close as _close

    if fignum is None:
        for fignum in get_fignums():
            _close(fignum)
    else:
        _close(fignum)


# -----------------------------------------------------------------------------
# locale utilities 
Example 29
Project: ble5-nrf52-mac   Author: tomasero   File: decorators.py    MIT License 5 votes vote down vote up
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 
Example 30
Project: nanopores   Author: mitschabaude   File: utilities.py    MIT License 5 votes vote down vote up
def saveplots(name="plot", meta=None, uid=False):
    # collect data from every open figure
    plots = []
    figs = map(plt.figure, plt.get_fignums())
    for fig in figs:
        for ax in fig.axes:
            plot = dict(
                xlabel = ax.get_xlabel(),
                ylabel = ax.get_ylabel(),
                xscale = ax.get_xscale(),
                yscale = ax.get_yscale(),
                data = [])
            for line in ax.lines:
                x, y = line.get_data()
                marker = line.get_marker()
                if marker == "None":
                    marker = ""
                data = dict(
                    x = x,
                    y = y,
                    style = marker + line.get_linestyle(),
                    label = line.get_label())
                plot["data"].append(data)
            plots.append(plot)
    # add metadata if provided
    meta = {} if meta is None else meta
    data = dict(plots=plots, meta=meta)
    # save to txt file in DATADIR
    DIR = os.path.join(DATADIR, "plots")
    name = name + "_" + str(unique_id()) if uid else name
    save_dict(data, DIR, name)
    return plots 
Example 31
Project: Computable   Author: ktraunmueller   File: figure.py    MIT License 5 votes vote down vote up
def __setstate__(self, state):
        version = state.pop('__mpl_version__')
        restore_to_pylab = state.pop('_restore_to_pylab', False)

        if version != _mpl_version:
            import warnings
            warnings.warn("This figure was saved with matplotlib version %s "
                          "and is unlikely to function correctly." %
                          (version, ))

        self.__dict__ = state

        # re-initialise some of the unstored state information
        self._axobservers = []
        self.canvas = None

        if restore_to_pylab:
            # lazy import to avoid circularity
            import matplotlib.pyplot as plt
            import matplotlib._pylab_helpers as pylab_helpers
            allnums = plt.get_fignums()
            num = max(allnums) + 1 if allnums else 1
            mgr = plt._backend_mod.new_figure_manager_given_figure(num, self)

            # XXX The following is a copy and paste from pyplot. Consider
            # factoring to pylab_helpers

            if self.get_label():
                mgr.set_window_title(self.get_label())

            # make this figure current on button press event
            def make_active(event):
                pylab_helpers.Gcf.set_active(mgr)

            mgr._cidgcf = mgr.canvas.mpl_connect('button_press_event',
                                                 make_active)

            pylab_helpers.Gcf.set_active(mgr)
            self.number = num

            plt.draw_if_interactive() 
Example 32
Project: Computable   Author: ktraunmueller   File: testing.py    MIT License 5 votes vote down vote up
def close(fignum=None):
    from matplotlib.pyplot import get_fignums, close as _close

    if fignum is None:
        for fignum in get_fignums():
            _close(fignum)
    else:
        _close(fignum) 
Example 33
Project: DevilYuan   Author: moyuanz   File: DyCommon.py    MIT License 5 votes vote down vote up
def newFig():
        figs = plt.get_fignums()

        for fig in range(1, DyMatplotlib.figNbr + 1):
            if fig not in figs:
                plt.figure(fig)
                DyMatplotlib.curFigNums.append(fig)
                return

        fig = DyMatplotlib.curFigNums[0]
        plt.close(fig)
        plt.figure(fig)

        del DyMatplotlib.curFigNums[0]
        DyMatplotlib.curFigNums.append(fig) 
Example 34
Project: pylustrator   Author: rgerum   File: drag_bib.py    GNU General Public License v3.0 5 votes vote down vote up
def StartPylustrator(xsnaps=None, ysnaps=None, unit="cm"):
    import matplotlib as mpl
    mpl.rcParams['keymap.back'].remove('left')
    mpl.rcParams['keymap.forward'].remove('right')

    # add a dragger for each figure
    for i in plt.get_fignums():
        print("add difgure dragger", plt.figure(i))
        FigureDragger(plt.figure(i), xsnaps, ysnaps, unit) 
Example 35
Project: neural-network-animation   Author: miloharper   File: figure.py    MIT License 5 votes vote down vote up
def __setstate__(self, state):
        version = state.pop('__mpl_version__')
        restore_to_pylab = state.pop('_restore_to_pylab', False)

        if version != _mpl_version:
            import warnings
            warnings.warn("This figure was saved with matplotlib version %s "
                          "and is unlikely to function correctly." %
                          (version, ))

        self.__dict__ = state

        # re-initialise some of the unstored state information
        self._axobservers = []
        self.canvas = None

        if restore_to_pylab:
            # lazy import to avoid circularity
            import matplotlib.pyplot as plt
            import matplotlib._pylab_helpers as pylab_helpers
            allnums = plt.get_fignums()
            num = max(allnums) + 1 if allnums else 1
            mgr = plt._backend_mod.new_figure_manager_given_figure(num, self)

            # XXX The following is a copy and paste from pyplot. Consider
            # factoring to pylab_helpers

            if self.get_label():
                mgr.set_window_title(self.get_label())

            # make this figure current on button press event
            def make_active(event):
                pylab_helpers.Gcf.set_active(mgr)

            mgr._cidgcf = mgr.canvas.mpl_connect('button_press_event',
                                                 make_active)

            pylab_helpers.Gcf.set_active(mgr)
            self.number = num

            plt.draw_if_interactive() 
Example 36
Project: dissecting-reinforcement-learning   Author: mpatacchiola   File: sarsa_mountain_car.py    MIT License 5 votes vote down vote up
def plot_curve(data_list, filepath="./my_plot.png",
               x_label="X", y_label="Y",
               x_range=(0, 1), y_range=(0,1), color="-r", kernel_size=50, alpha=0.4, grid=True):
        """Plot a graph using matplotlib

        """
        if(len(data_list) <=1):
            print("[WARNING] the data list is empty, no plot will be saved.")
            return
        fig = plt.figure()
        ax = fig.add_subplot(111, autoscale_on=False, xlim=x_range, ylim=y_range)
        ax.grid(grid)
        ax.set_xlabel(x_label)
        ax.set_ylabel(y_label)
        ax.plot(data_list, color, alpha=alpha)  # The original data is showed in background
        kernel = np.ones(int(kernel_size))/float(kernel_size)  # Smooth the graph using a convolution
        tot_data = len(data_list)
        lower_boundary = int(kernel_size/2.0)
        upper_boundary = int(tot_data-(kernel_size/2.0))
        data_convolved_array = np.convolve(data_list, kernel, 'same')[lower_boundary:upper_boundary]
        #print("arange: " + str(np.arange(tot_data)[lower_boundary:upper_boundary]))
        #print("Convolved: " + str(np.arange(tot_data).shape))
        ax.plot(np.arange(tot_data)[lower_boundary:upper_boundary], data_convolved_array, color, alpha=1.0)  # Convolved plot
        fig.savefig(filepath)
        fig.clear()
        plt.close(fig)
        # print(plt.get_fignums())  # print the number of figures opened in background 
Example 37
Project: dissecting-reinforcement-learning   Author: mpatacchiola   File: temporal_differencing_control_sarsa.py    MIT License 5 votes vote down vote up
def plot_curve(data_list, filepath="./my_plot.png", x_label="X", y_label="Y",
               x_range=(0, 1), y_range=(0,1), color="-r", kernel_size=50,
               alpha=0.4, grid=True):
        """Plot a graph using matplotlib

        """
        if(len(data_list) <=1): return
        fig = plt.figure()
        ax = fig.add_subplot(111, autoscale_on=False, xlim=x_range, ylim=y_range)
        ax.grid(grid)
        ax.set_xlabel(x_label)
        ax.set_ylabel(y_label)
        # The original data is showed in background
        ax.plot(data_list, color, alpha=alpha)
        # Smooth the graph using a convolution
        kernel = np.ones(int(kernel_size))/float(kernel_size)
        tot_data = len(data_list)
        lower_boundary = int(kernel_size/2.0)
        upper_boundary = int(tot_data-(kernel_size/2.0))
        data_convolved_array = np.convolve(data_list, kernel, 'same')[lower_boundary:upper_boundary]
        #print("arange: " + str(np.arange(tot_data)[lower_boundary:upper_boundary]))
        #print("Convolved: " + str(np.arange(tot_data).shape))
        ax.plot(np.arange(tot_data)[lower_boundary:upper_boundary],
                data_convolved_array, color, alpha=1.0)  # Convolved plot
        fig.savefig(filepath)
        fig.clear()
        plt.close(fig)
        # print(plt.get_fignums())  # print the number of figures opened in background 
Example 38
Project: dissecting-reinforcement-learning   Author: mpatacchiola   File: qlearning_drone_landing.py    MIT License 5 votes vote down vote up
def plot_curve(data_list, filepath="./my_plot.png", 
               x_label="X", y_label="Y", 
               x_range=(0, 1), y_range=(0,1), color="-r", kernel_size=50, alpha=0.4, grid=True):
        """Plot a graph using matplotlib

        """
        if(len(data_list) <=1):
            print("[WARNING] the data list is empty, no plot will be saved.")
            return
        fig = plt.figure()
        ax = fig.add_subplot(111, autoscale_on=False, xlim=x_range, ylim=y_range)
        ax.grid(grid)
        ax.set_xlabel(x_label)
        ax.set_ylabel(y_label)
        ax.plot(data_list, color, alpha=alpha)  # The original data is showed in background
        kernel = np.ones(int(kernel_size))/float(kernel_size)  # Smooth the graph using a convolution
        tot_data = len(data_list)
        lower_boundary = int(kernel_size/2.0)
        upper_boundary = int(tot_data-(kernel_size/2.0))
        data_convolved_array = np.convolve(data_list, kernel, 'same')[lower_boundary:upper_boundary]
        #print("arange: " + str(np.arange(tot_data)[lower_boundary:upper_boundary]))
        #print("Convolved: " + str(np.arange(tot_data).shape))
        ax.plot(np.arange(tot_data)[lower_boundary:upper_boundary], data_convolved_array, color, alpha=1.0)  # Convolved plot
        fig.savefig(filepath)
        fig.clear()
        plt.close(fig)
        # print(plt.get_fignums())  # print the number of figures opened in background 
Example 39
Project: dissecting-reinforcement-learning   Author: mpatacchiola   File: montecarlo_control_inverted_pendulum.py    MIT License 5 votes vote down vote up
def plot_curve(data_list, filepath="./my_plot.png", 
               x_label="X", y_label="Y", 
               x_range=(0, 1), y_range=(0,1), color="-r", kernel_size=50, alpha=0.4, grid=True):
        """Plot a graph using matplotlib

        """
        if(len(data_list) <=1):
            print("[WARNING] the data list is empty, no plot will be saved.")
            return
        fig = plt.figure()
        ax = fig.add_subplot(111, autoscale_on=False, xlim=x_range, ylim=y_range)
        ax.grid(grid)
        ax.set_xlabel(x_label)
        ax.set_ylabel(y_label)
        ax.plot(data_list, color, alpha=alpha)  # The original data is showed in background
        kernel = np.ones(int(kernel_size))/float(kernel_size)  # Smooth the graph using a convolution
        tot_data = len(data_list)
        lower_boundary = int(kernel_size/2.0)
        upper_boundary = int(tot_data-(kernel_size/2.0))
        data_convolved_array = np.convolve(data_list, kernel, 'same')[lower_boundary:upper_boundary]
        #print("arange: " + str(np.arange(tot_data)[lower_boundary:upper_boundary]))
        #print("Convolved: " + str(np.arange(tot_data).shape))
        ax.plot(np.arange(tot_data)[lower_boundary:upper_boundary], data_convolved_array, color, alpha=1.0)  # Convolved plot
        fig.savefig(filepath)
        fig.clear()
        plt.close(fig)
        # print(plt.get_fignums())  # print the number of figures opened in background 
Example 40
Project: GraphicDesignPatternByPython   Author: Relph1119   File: decorators.py    MIT License 5 votes vote down vote up
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 
Example 41
Project: psyplot   Author: Chilipp   File: project.py    GNU General Public License v2.0 5 votes vote down vote up
def load_figure(d, new_fig=True):
        """Create a figure from what is returned by :meth:`inspect_figure`"""
        import matplotlib.pyplot as plt
        subplotpars = d.pop('subplotpars', None)
        if subplotpars is not None:
            subplotpars.pop('validate', None)
            subplotpars = mfig.SubplotParams(**subplotpars)
        if new_fig:
            nums = plt.get_fignums()
            if d.get('num') in nums:
                d['num'] = next(
                    i for i in range(max(plt.get_fignums()) + 1, 0, -1)
                    if i not in nums)
        return plt.figure(subplotpars=subplotpars, **d) 
Example 42
Project: psyplot   Author: Chilipp   File: test_project.py    GNU General Public License v2.0 5 votes vote down vote up
def test_one_subplot(self):
        plt.close('all')
        axes = psy.multiple_subplots()
        self.assertEqual(len(axes), 1)
        self.assertEqual(plt.get_fignums(), [1])
        self.assertEqual(len(plt.gcf().axes), 1)
        self.assertIs(axes[0], plt.gcf().axes[0])
        plt.close('all') 
Example 43
Project: psyplot   Author: Chilipp   File: test_project.py    GNU General Public License v2.0 5 votes vote down vote up
def test_multiple_subplots(self):
        plt.close('all')
        axes = psy.multiple_subplots(2, 2, 3, 5)
        self.assertEqual(len(axes), 5)
        self.assertEqual(plt.get_fignums(), [1, 2])
        self.assertEqual(len(plt.figure(1).axes), 3)
        self.assertEqual(len(plt.figure(2).axes), 2)
        it_ax = iter(axes)
        for ax2 in chain(plt.figure(1).axes, plt.figure(2).axes):
            self.assertIs(next(it_ax), ax2)
        plt.close('all') 
Example 44
Project: L2RPN   Author: shidi1985   File: evaluate.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def save_figures():
    fig_list = list()
    for i in plt.get_fignums():
        fig = plt.figure(i)
        figfile = BytesIO()
        # fig.set_size_inches(12)
        plt.savefig(figfile, format='png')  # ,dpi=100)
        figfile.seek(0)
        fig_list.append(base64.b64encode(figfile.getvalue()).decode('ascii'))
        plt.close(fig)
    return fig_list 
Example 45
Project: predictive-maintenance-using-machine-learning   Author: awslabs   File: testing.py    Apache License 2.0 5 votes vote down vote up
def close(fignum=None):
    from matplotlib.pyplot import get_fignums, close as _close

    if fignum is None:
        for fignum in get_fignums():
            _close(fignum)
    else:
        _close(fignum)


# -----------------------------------------------------------------------------
# locale utilities 
Example 46
Project: fund   Author: Frank-qlu   File: testing.py    Apache License 2.0 5 votes vote down vote up
def close(fignum=None):
    from matplotlib.pyplot import get_fignums, close as _close

    if fignum is None:
        for fignum in get_fignums():
            _close(fignum)
    else:
        _close(fignum)


# -----------------------------------------------------------------------------
# locale utilities 
Example 47
Project: bayescreen   Author: davidhoksza   File: analyze_model.py    MIT License 5 votes vote down vote up
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() 
Example 48
Project: psychrometric-chart-makeover   Author: buds-lab   File: decorators.py    MIT License 5 votes vote down vote up
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 
Example 49
Project: psychrometric-chart-makeover   Author: buds-lab   File: testing.py    MIT License 5 votes vote down vote up
def close(fignum=None):
    from matplotlib.pyplot import get_fignums, close as _close

    if fignum is None:
        for fignum in get_fignums():
            _close(fignum)
    else:
        _close(fignum)


# -----------------------------------------------------------------------------
# locale utilities 
Example 50
Project: pyxem   Author: pyxem   File: peakfinder2D_gui.py    GNU General Public License v3.0 5 votes vote down vote up
def replot_image(self):
        if not plt.get_fignums():
            self.plot()
        z = self.get_data()
        self.image.set_data(z)
        self.replot_peaks()
        plt.draw()