Python matplotlib.pyplot 模块,switch_backend() 实例源码

我们从Python开源项目中,提取了以下10个代码示例,用于说明如何使用matplotlib.pyplot.switch_backend()

项目:pytomo3d    作者:computational-seismology    | 项目源码 | 文件源码
def reset_matplotlib():
    """
    Reset matplotlib to a common default.
    """
    # Set all default values.
    mpl.rcdefaults()
    # Force agg backend.
    plt.switch_backend('agg')
    # These settings must be hardcoded for running the comparision tests and
    # are not necessarily the default values.
    mpl.rcParams['font.family'] = 'Bitstream Vera Sans'
    mpl.rcParams['text.hinting'] = False
    # Not available for all matplotlib versions.
    try:
        mpl.rcParams['text.hinting_factor'] = 8
    except KeyError:
        pass
    import locale
    locale.setlocale(locale.LC_ALL, str('en_US.UTF-8'))


# Most generic way to get the data folder path.
项目:pytomo3d    作者:computational-seismology    | 项目源码 | 文件源码
def test_calculate_adjsrc_on_trace_figure_mode_none_figure_dir():
    obs, syn, win_time = setup_calculate_adjsrc_on_trace_args()
    config = load_config_multitaper()
    plt.switch_backend('agg')
    adjsrc = adj.calculate_adjsrc_on_trace(
        obs, syn, win_time, config, adj_src_type="multitaper_misfit",
        figure_mode=True)
    assert adjsrc


# def test_calculate_adjsrc_on_trace_waveform_misfit_produces_adjsrc():
#    obs, syn, win_time = setup_calculate_adjsrc_on_trace_args()
#    config = load_config_waveform()

#    adjsrc = adj.calculate_adjsrc_on_trace(
#        obs, syn, win_time, config, adj_src_type="waveform_misfit",
#        adjoint_src_flag=True, figure_mode=False)
#    assert adjsrc
项目:latexipy    作者:masasin    | 项目源码 | 文件源码
def latexify(params=PARAMS, new_backend='pgf'):
    '''
    Set up Matplotlib's RC params for LaTeX plotting.

    Call this function before plotting the first figure.

    Parameters
    ----------
    params : Optional[dict]
        A dictionary containing the RC params that need to be updated. Default
        is ``PARAMS``. The defaults should be okay for most cases, but
        ``PARAMS`` can be updated via ``.update()`` as well.

    new_backend : Optional[str|None]
        The backend to switch too. Default is PGF, which allows a nicer PDF
        output too.

    Raises
    ------
    ValueError
        If the new backend is not supported.

    Example
    -------
    >>> params = PARAMS.copy()
    >>> params.update({'font.family': 'sans-serif'})
    >>> latexify(params)

    '''
    plt.rcParams.update(params)
    if new_backend is not None:
        try:
            plt.switch_backend(new_backend)
        except ValueError:
            logger.error(f'Backend not supported: {new_backend!r}')
            raise
项目:latexipy    作者:masasin    | 项目源码 | 文件源码
def revert():
    '''
    Return to the settings before running ``latexify()`` and updating params.

    '''
    plt.rcParams.update(_ORIGINAL_PARAMS)
    plt.switch_backend(_ORIGINAL_BACKEND)
项目:plotnine    作者:has2k1    | 项目源码 | 文件源码
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())
项目:pytomo3d    作者:computational-seismology    | 项目源码 | 文件源码
def reset_matplotlib():
    """
    Reset matplotlib to a common default.
    """
    # Set all default values.
    mpl.rcdefaults()
    # Force agg backend.
    plt.switch_backend('agg')
项目:partycrasher    作者:naturalness    | 项目源码 | 文件源码
def test(self):
        nr_observations = sum(self.histogram)
        observed_frequencies = []
        expected_frequencies = []
        frequencies_of = []
        thresh = 10
        for i in range(0, len(self.histogram)):
            observed = self.histogram[i]
            expected = stats.poisson.pmf(i, self.lambda_) * nr_observations
            if (
                (observed >= thresh)
                and (expected >= thresh)):
                observed_frequencies.append(observed)
                expected_frequencies.append(expected)
                frequencies_of.append(i)
        results = stats.chisquare(observed_frequencies,
                                  expected_frequencies)
        print("expected: mean %f variance %f" % (
                      self.expected_mean(),
                      self.expected_variance()))
        print("actual: mean %f variance %f" % (
                      self.mean(),
                      self.variance()))
        print(len(expected_frequencies))
        print(results)
        from matplotlib import pyplot
        import matplotlib
        pyplot.switch_backend('Qt5Agg')
        actual_plot, = pyplot.plot(frequencies_of, observed_frequencies, label='actual')
        expected_plot, = pyplot.plot(frequencies_of, expected_frequencies, 'r', linewidth=1, label='expected')
        matplotlib.interactive(True)
        #pyplot.ylabel("People at Table")
        #pyplot.xlabel("Table Number")
        #pyplot.title("Chinese Restaurant Process Unit Test")
        pyplot.legend()
        pyplot.show(block=True)
        return results
项目:partycrasher    作者:naturalness    | 项目源码 | 文件源码
def test_chinese_restaurant_process(self):
        print(sys.path)
        from matplotlib import pyplot
        import matplotlib
        from scipy import stats
        alpha = 20
        test_size = 1000
        tests = 1000
        data = [0]
        for j in range(0, tests):
            cr = ChineseRestaurant(alpha, Numbers())
            for i in range(0, test_size):
                new_sample = cr.draw()
                if new_sample >= len(data):
                    data.append(0)
                data[new_sample] += 1
            assert cr.heap[1] == test_size
        pyplot.switch_backend('Qt5Agg')
        #data=sorted(data, reverse=True)
        print(len(data))
        actual_plot, = pyplot.plot(range(1,len(data)), data[1:], label='actual avg')
        expected = [0]
        remain = test_size * tests
        for i in range(1, len(data)):
            break_ = stats.beta.mean(1.0, float(alpha)) * remain
            expected.append(break_)
            remain -= break_
        #print est
        expected_plot, = pyplot.plot(range(1,len(data)), expected[1:], 'r', linewidth=1, label='expected')
        matplotlib.interactive(True)
        pyplot.ylabel("People at Table")
        pyplot.xlabel("Table Number")
        pyplot.title("Chinese Restaurant Process Unit Test")
        pyplot.legend()
        pyplot.show(block=True)
项目:msnoise-tomo    作者:ThomasLecocq    | 项目源码 | 文件源码
def main():
    import matplotlib.pyplot as plt
    plt.switch_backend("agg")
    import os
    import sys


    suite = unittest.defaultTestLoader.loadTestsFromTestCase(MSNoiseTomoTests)
    runner = unittest.TextTestRunner(verbosity=4)
    result = runner.run(suite)
    if not result.wasSuccessful():
        sys.exit(1)
项目:latenttrees    作者:kaltwang    | 项目源码 | 文件源码
def check_matplotlib_backends():
    # from http://stackoverflow.com/questions/5091993/list-of-all-available-matplotlib-backends
    # get the directory where the backends live
    backends_dir = os.path.dirname(matplotlib.backends.__file__)

    # filter all files in that directory to identify all files which provide a backend
    backend_fnames = filter(is_backend_module, os.listdir(backends_dir))

    backends = [backend_fname_formatter(fname) for fname in backend_fnames]

    print("supported backends: \t" + str(backends))

    # validate backends
    backends_valid = []
    for b in backends:
        try:
            plt.switch_backend(b)
            backends_valid += [b]
        except:
            continue

    print("valid backends: \t" + str(backends_valid))


    # try backends performance
    for b in backends_valid:

        pylab.ion()
        try:
            plt.switch_backend(b)


            pylab.clf()
            tstart = time.time()               # for profiling
            x = range(0,2*pylab.pi,0.01)            # x-array
            line, = pylab.plot(x,pylab.sin(x))
            for i in range(1,200):
                line.set_ydata(pylab.sin(x+i/10.0))  # update the data
                pylab.draw()                         # redraw the canvas

            print(b + ' FPS: \t' , 200/(time.time()-tstart))
            pylab.ioff()

        except:
            print(b + " error :(")