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

Python pyplot.switch_backend函数代码示例

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

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



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

示例1: test_asc

def test_asc():
    mean1 = [0.5, 0.5]
    mean2 = [3.0, 0.5]
    conv1 = [[1, 0], [0, 1]]
    conv2 = [[1.5, 0], [0, 1.2]]
    samples = 2000
    class1_data = np.random.multivariate_normal(mean1, conv1, samples)
    class1_label = np.ones(samples, dtype=np.int32) * 0
    class2_data = np.random.multivariate_normal(mean2, conv2, samples)
    class2_label = np.ones(samples, dtype=np.int32) * 1
    train_data = np.concatenate((class1_data, class2_data))
    train_label = np.concatenate((class1_label, class2_label))

    prototypes, labels = asc(train_data, train_label, 20, 20, 3)
    plt.switch_backend('Qt4Agg')
    plt.figure(1)
    plt.hold(True)
    plt.plot(class1_data[:, 0], class1_data[:, 1], 'r*')
    plt.plot(class2_data[:, 0], class2_data[:, 1], 'b.')
    plt.figure(2)
    plt.hold(True)
    for i in xrange(labels.shape[0]):
        if labels[i] == 0:
            plt.plot(prototypes[i, 0], prototypes[i, 1], 'r*')
        else:
            plt.plot(prototypes[i, 0], prototypes[i, 1], 'b.')
    plt.hold(False)
    plt.show()
开发者ID:cyrobot,项目名称:soinn,代码行数:28,代码来源:asc.py


示例2: switch_backend

    def switch_backend(backend, sloppy=True):
        """
        Switch matplotlib backend.

        :type backend: str
        :param backend: Name of matplotlib backend to switch to.
        :type sloppy: bool
        :param sloppy: If ``True``, only uses
            :func:`matplotlib.pyplot.switch_backend` and no warning will be
            shown if the backend was not switched successfully. If ``False``,
            additionally tries to use :func:`matplotlib.use` first and also
            shows a warning if the backend was not switched successfully.
        """
        import matplotlib
        # sloppy. only do a `plt.switch_backend(..)`
        if sloppy:
            import matplotlib.pyplot as plt
            plt.switch_backend(backend)
        else:
            # check if `matplotlib.use(..)` is emitting a warning
            try:
                with warnings.catch_warnings(record=True):
                    warnings.simplefilter("error", UserWarning)
                    matplotlib.use(backend)
            # if that's the case, follow up with `plt.switch_backend(..)`
            except UserWarning:
                import matplotlib.pyplot as plt
                plt.switch_backend(backend)
            # finally check if the switch was successful,
            # show a warning if not
            if matplotlib.get_backend().upper() != backend.upper():
                msg = "Unable to change matplotlib backend to '%s'" % backend
                warnings.warn(msg)
开发者ID:adakite,项目名称:obspy,代码行数:33,代码来源:misc.py


示例3: has_matplotlib

def has_matplotlib(version=None, op=">="):
    """
    True if matplotlib_ is installed.
    If version is None, the result of matplotlib.__version__ `op` version is returned.
    """
    try:
        import matplotlib
        # have_display = "DISPLAY" in os.environ
    except ImportError:
        print("Skipping matplotlib test")
        return False

    matplotlib.use("Agg")
    #matplotlib.use("Agg", force=True)  # Use non-graphical display backend during test.
    import matplotlib.pyplot as plt
    # http://stackoverflow.com/questions/21884271/warning-about-too-many-open-figures
    plt.close("all")

    backend = matplotlib.get_backend()
    if backend.lower() != "agg":
        #raise RuntimeError("matplotlib backend now is %s" % backend)
        #matplotlib.use("Agg", warn=True, force=False)
        # Switch the default backend.
        # This feature is experimental, and is only expected to work switching to an image backend.
        plt.switch_backend("Agg")

    if version is None: return True
    return cmp_version(matplotlib.__version__, version, op=op)
开发者ID:gpetretto,项目名称:abipy,代码行数:28,代码来源:testing.py


示例4: plot

    def plot(self, filedir=None, file_format='pdf'):
        if filedir is None:
            filedir = self.workdir
        import matplotlib.pyplot as plt
        plt.switch_backend('agg')

        plt.figure(figsize=(8, 6))
        plt.subplots_adjust(left=0.1, bottom=0.08, right=0.95, top=0.95, wspace=None, hspace=None)
        forces = np.array(self.output['forces'])
        maxforce = [np.max(np.apply_along_axis(np.linalg.norm, 1, x)) for x in forces]
        avgforce = [np.mean(np.apply_along_axis(np.linalg.norm, 1, x)) for x in forces]

        if np.max(maxforce) > 0.0 and np.max(avgforce) > 0.0:
            plt.semilogy(maxforce, 'b.-', label='Max force')
            plt.semilogy(avgforce, 'r.-', label='Mean force')
        else:
            plt.plot(maxforce, 'b.-', label='Max force')
            plt.plot(avgforce, 'r.-', label='Mean force')
        plt.xlabel('Ion movement iteration')
        plt.ylabel('Max Force')
        plt.savefig(filedir + os.sep + 'forces.' + file_format)
        plt.clf()

        plt.figure(figsize=(8, 6))
        plt.subplots_adjust(left=0.1, bottom=0.08, right=0.95, top=0.95, wspace=None, hspace=None)
        stress = np.array(self.output['stress'])
        diag_stress = [np.trace(np.abs(x)) for x in stress]
        offdiag_stress = [np.sum(np.abs(np.triu(x, 1).flatten())) for x in stress]
        plt.semilogy(diag_stress, 'b.-', label='diagonal')
        plt.semilogy(offdiag_stress, 'r.-', label='off-diagonal')
        plt.legend()
        plt.xlabel('Ion movement iteration')
        plt.ylabel(r'$\sum |stress|$ (diag, off-diag)')
        plt.savefig(filedir + os.sep + 'stress.' + file_format)
开发者ID:apayne9,项目名称:PyChemia,代码行数:34,代码来源:relax.py


示例5: createFFT

def createFFT(data, cols, currentAnalysis):
    plt.switch_backend('agg')
    fg, ax = plt.subplots()
    plt.title('FFT - ' + cols[0])
    plotting.fft(data.data, cols[0], ax)
    createDirForPlot(currentAnalysis)
    plt.savefig(STATIC_DIR + '/plots/' + currentAnalysis.title +'/fft.png')
开发者ID:liamo7,项目名称:WindAnalysisCoursework,代码行数:7,代码来源:analysis.py


示例6: ecg2rri

def ecg2rri(x):
    global rri, t, ax2, pos_c
    pos_c = []
    plt.switch_backend('qt4Agg')
    plt.ion()
    msg = "RRi Detection Parameters"
    title = "Parameters Dialog"
    fieldNames = ["Threshold", "Refractory Period", "Low Cuttof Freq.",
                  "Upper Cuttof Freq.", "Sampling Frequency"]
    fieldValues = ["0.5", "200", "5", "40", "1000"]
    fieldValues = multenterbox(msg, title, fieldNames, fieldValues)
    fieldValues = [float(k) for k in fieldValues]
    thr = fieldValues[0]
    Fs = fieldValues[4]
    lC = fieldValues[2] / (0.5 * Fs)  #normalized lower cutoff frequency.
    uC = fieldValues[3] / (0.5 * Fs)  #normalized upper cutoff frequency.
    B, A = butter(4, [lC, uC], 'band')
    xf = filtfilt(B, A, x)  #filtered ecg.
    xd = diff(xf)  #first derivative of the ecg.
    peaks = array([peaks + 1 for peaks in xrange(len(xd)) if xd[peaks] > 0 and
        xd[peaks + 1] < 0 and xf[peaks] > thr or xd[peaks] == 0])  #find RR peaks above threshold.

    rri = diff(peaks)  # RRi in miliseconds
    t = cumsum(rri) / 1000.0
    t_ecg = arange(0, len(xf)) / Fs
    fig = plt.figure()
    ax1 = fig.add_subplot(2, 1, 1)
    ax2 = fig.add_subplot(2, 1, 2)
    ax1.plot(t_ecg, xf)
    ax1.plot(t_ecg[peaks], xf[peaks], 'g.-')
    ax2.plot(t, rri, 'k.-')
    fig.canvas.mpl_connect('button_press_event', onclick)
    return t, rri
开发者ID:RhenanBartels,项目名称:Spectral-Tools,代码行数:33,代码来源:pyecg.py


示例7: testPlot

    def testPlot(self):
        """Test plotting of spectrum

        Not easy to test the actual result, but we can test that the API hasn't
        been broken.
        """
        import matplotlib.pyplot as plt
        plt.switch_backend("agg")  # In case someone has loaded a different backend that will cause trouble
        ext = ".png"  # Extension to use for plot filenames
        spectrum = self.makeSpectrum()
        # Write directly to file
        with lsst.utils.tests.getTempFilePath(ext) as filename:
            spectrum.plot(numRows=4, doBackground=True, doReferenceLines=True, filename=filename)
        # Check return values
        with lsst.utils.tests.getTempFilePath(ext) as filename:
            numRows = 4  # Must be > 1 for len(axes) to work
            figure, axes = spectrum.plot(numRows=numRows)
            self.assertEqual(len(axes), numRows)
            figure.savefig(filename)
        # Test one row, write directly to file
        with lsst.utils.tests.getTempFilePath(ext) as filename:
            figure, axes = spectrum.plot(numRows=1, filename=filename)
        # Test one row, check return values
        with lsst.utils.tests.getTempFilePath(ext) as filename:
            figure, axes = spectrum.plot(numRows=1)
            with self.assertRaises(TypeError):
                axes[0]
            figure.savefig(filename)
开发者ID:Subaru-PFS,项目名称:drp_stella,代码行数:28,代码来源:test_Spectrum.py


示例8: test_chinese_restaurant_process

 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)
开发者ID:naturalness,项目名称:partycrasher,代码行数:35,代码来源:fake_data_generator.py


示例9: test_QueueNetwork_animate

 def test_QueueNetwork_animate(self):
     if not HAS_MATPLOTLIB:
         with mock.patch('queueing_tool.network.queue_network.plt.show'):
             self.qn.animate(frames=5)
     else:
         plt.switch_backend('Agg')
         self.qn.animate(frames=5)
开发者ID:djordon,项目名称:queueing-tool,代码行数:7,代码来源:test_network.py


示例10: movie

    def movie(self,di=10, coord='latlon',land="nice", heatmap=False):
        curr_backend = plt.get_backend()
        plt.switch_backend('Agg')

        FFMpegWriter = animation.writers['ffmpeg']
        metadata = dict(title='%s %s' % (self.projname, self.casename),
                        artist='pytraj',
                        comment='https://github.com/TRACMASS/pytraj')
        writer = FFMpegWriter(fps=15, metadata=metadata)

        fig = plt.figure()
        with writer.saving(fig, "traj_test.mp4", 200):
            for part in self.partvec:
                self.load(part=part)
                jdvec = np.sort(self.jdvec)                
                for jd in jdvec:
                    print part, jdvec[-1] - jd, len(self.jd[self.jd==jd])
                    if len(self.jd[self.jd==jd]) <= 1: continue
                    if jd/di == float(jd)/di:
                        if heatmap == True:
                            self.heatmap(log=True, jd=jd)
                        else:
                            self.scatter(jd=jd, coord=coord, land=land)
                        writer.grab_frame()
        plt.switch_backend(curr_backend)
开发者ID:brorfred,项目名称:pytraj,代码行数:25,代码来源:traj.py


示例11: _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


示例12: main

def main():

    dataDir = sys.argv[1]
    dataType = "train2014"

    plt.switch_backend("TkAgg")
    pylab.rcParams['figure.figsize'] = (15.0, 10.0)

    ct = coco_text.COCO_Text(sys.argv[2])
    ct.info()

    # get all images containing at least one instance of legible text
    imgIds = ct.getImgIds(imgIds=ct.train, 
                                catIds=[('legibility','legible')])

    while True:
        # pick one at random
        img = ct.loadImgs(imgIds[np.random.randint(0,len(imgIds))])[0]

        I = io.imread('%s/images/%s/%s'%(dataDir,dataType,img['file_name']))
        print '/images/%s/%s'%(dataType,img['file_name'])
        plt.figure()
        annIds = ct.getAnnIds(imgIds=img['id'])
        anns = ct.loadAnns(annIds)
        ct.showAnns(anns)
        plt.imshow(I)
        plt.show()
开发者ID:ashwin,项目名称:coco-text,代码行数:27,代码来源:coco_explorer.py


示例13: test_plot_connectome

def test_plot_connectome():
    import matplotlib.pyplot as plt
    plt.switch_backend('template')
    node_color = ['green', 'blue', 'k', 'cyan']
    # symmetric up to 1e-3 relative tolerance
    adjacency_matrix = np.array([[1., -2., 0.3, 0.],
                                 [-2.002, 1, 0., 0.],
                                 [0.3, 0., 1., 0.],
                                 [0., 0., 0., 1.]])
    node_coords = np.arange(3 * 4).reshape(4, 3)

    args = adjacency_matrix, node_coords
    kwargs = dict(edge_threshold=0.38,
                  title='threshold=0.38',
                  node_size=10, node_color=node_color)
    plot_connectome(*args, **kwargs)

    # used to speed-up tests for the next plots
    kwargs['display_mode'] = 'x'

    # node_coords not an array but a list of tuples
    plot_connectome(adjacency_matrix,
                    [tuple(each) for each in node_coords],
                    **kwargs)
    # saving to file
    with tempfile.NamedTemporaryFile(suffix='.png') as fp:
        display = plot_connectome(*args, output_file=fp.name,
                                  **kwargs)
        assert_true(display is None)
        assert_true(os.path.isfile(fp.name) and
                    os.path.getsize(fp.name) > 0)

    # with node_kwargs, edge_kwargs and edge_cmap arguments
    plot_connectome(*args,
                    edge_threshold='70%',
                    node_size=[10, 20, 30, 40],
                    node_color=np.zeros((4, 3)),
                    edge_cmap='RdBu',
                    node_kwargs={
                        'marker': 'v'},
                    edge_kwargs={
                        'linewidth': 4})

    # masked array support
    masked_adjacency_matrix = np.ma.masked_array(
        adjacency_matrix, np.abs(adjacency_matrix) < 0.5)
    plot_connectome(masked_adjacency_matrix, node_coords,
                    **kwargs)

    # sparse matrix support
    sparse_adjacency_matrix = sparse.coo_matrix(adjacency_matrix)
    plot_connectome(sparse_adjacency_matrix, node_coords,
                    **kwargs)

    # NaN matrix support
    nan_adjacency_matrix = np.array([[1., np.nan, 0.],
                                     [np.nan, 1., 2.],
                                     [np.nan, 2., 1.]])
    nan_node_coords = np.arange(3 * 3).reshape(3, 3)
    plot_connectome(nan_adjacency_matrix, nan_node_coords, **kwargs)
开发者ID:fabianp,项目名称:nilearn,代码行数:60,代码来源:test_img_plotting.py


示例14: test_plot_stat_map

def test_plot_stat_map():
    mp.use('template', warn=False)
    import matplotlib.pyplot as plt
    plt.switch_backend('template')
    img = _generate_img()

    plot_stat_map(img, cut_coords=(80, -120, -60))

    # Smoke test coordinate finder, with and without mask
    masked_img = nibabel.Nifti1Image(
        np.ma.masked_equal(img.get_data(), 0),
        mni_affine)
    plot_stat_map(masked_img, display_mode='x')
    plot_stat_map(img, display_mode='y', cut_coords=2)

    # 'yx' display_mode
    plot_stat_map(img, display_mode='yx')

    # regression test #510
    data = np.zeros((91, 109, 91))
    aff = np.eye(4)
    new_img = nibabel.Nifti1Image(data, aff)
    plot_stat_map(new_img, threshold=1000, colorbar=True)

    rng = np.random.RandomState(42)
    data = rng.randn(91, 109, 91)
    new_img = nibabel.Nifti1Image(data, aff)
    plot_stat_map(new_img, threshold=1000, colorbar=True)
开发者ID:fabianp,项目名称:nilearn,代码行数:28,代码来源:test_img_plotting.py


示例15: main

def main():
    parser = get_parser()
    args = parser.parse_args()
    root = os.path.splitext(os.path.basename(args.cgmap))[0]
    ctxstr = const_ctxstr(args.fasta)
    cgmap = const_cgmap(ctxstr, args.cgmap, args.depth)
    gtftree = const_gtftree(args.gtf)
    bulk = calc_bulk(ctxstr, cgmap)
    plt.switch_backend('Agg')
    bulk_ax = plot_bulkmean(bulk)
    fig = bulk_ax.get_figure()
    fig.savefig('{}.bulk.mean.png'.format(root), dpi=300)
    plt.close(fig)
    bulk_fig = plot_bulkhist(bulk)
    bulk_fig.savefig('{}.bulk.hist.png'.format(root), dpi=300)
    plt.close(fig)
    ign, cg_table, chg_table, chh_table = calc_mlevel(ctxstr, cgmap, gtftree, args.pmtsize)
    cg_table.to_csv('{}.feature.CG.txt'.format(root), sep='\t', float_format='%.3f')
    chg_table.to_csv('{}.feature.CHG.txt'.format(root), sep='\t', float_format='%.3f')
    chh_table.to_csv('{}.feature.CHH.txt'.format(root), sep='\t', float_format='%.3f')
    cg_ax, chg_ax, chh_ax = plot_feature_mlevel(bulk, ign, cg_table, chg_table, chh_table)
    fig = cg_ax.get_figure()
    fig.savefig('{}.feature.CG.png'.format(root), dpi=300)
    plt.close(fig)
    fig = chg_ax.get_figure()
    fig.savefig('{}.feature.CHG.png'.format(root), dpi=300)
    plt.close(fig)
    fig = chh_ax.get_figure()
    fig.savefig('{}.feature.CHH.png'.format(root), dpi=300)
    plt.close(fig)
    gpos, gmlevel = calc_genomewide(ctxstr, cgmap)
    gax = plot_genomewide(ctxstr, gpos, gmlevel)
    fig = gax.get_figure()
    fig.savefig('{}.genomewide.png'.format(root), dpi=300)
    plt.close(fig)
开发者ID:xflicsu,项目名称:methgo,代码行数:35,代码来源:met.py


示例16: test

def test(target=None, show=False, onlydoctests=False, coverage=False, htmlreport=False):
    """Run docstring examples and additional tests.

    Examples
    --------
    >>> from pygimli.utils import boxprint
    >>> test(target=boxprint)

    Parameters
    ----------
    target : function, optional
        Function or method to test. By default everything is tested.
    show : boolean, optional
        Show matplotlib windows during test run. They will be closed
        automatically.
    onlydoctests : boolean, optional
        Run test files in ../tests as well.
    coverage : boolean, optional
        Create a coverage report. Requires the pytest-cov plugin.
    htmlreport : str, optional
        Filename for HTML report such as www.pygimli.org/build_tests.html.
        Requires pytest-html plugin.
    """
    if target:
        import doctest
        doctest.run_docstring_examples(target, globals())
        return

    try:
        import pytest
    except ImportError:
        raise ImportError("pytest is required to run test suite. " + \
                          "Try 'sudo pip install pytest'.")

    from matplotlib import pyplot as plt
    from pygimli.utils import opt_import
    pc = opt_import("pytest_cov", "create a code coverage report")
    ph = opt_import("pytest_html", "create a html report")

    old_backend = plt.get_backend()
    if not show:
        plt.switch_backend("Agg")
    cwd = os.path.realpath(__path__[0])
    cfg = os.path.join(cwd, "../tests/setup.cfg")
    cmd = ""
    if os.path.exists(cfg):
        cmd += "-c %s " % cfg
    if pc and coverage:
        cmd += "--cov pygimli --cov-report term " + \
               "--cov-config %s " % cfg.replace("setup.cfg", ".coveragerc")
    if ph and htmlreport:
        cmd += "--html %s " % htmlreport
    cmd += "%s " % cwd
    if not onlydoctests and os.path.exists(cfg):
        cmd += os.path.join(cwd, "../tests")

    exitcode = pytest.main(cmd)
    plt.switch_backend(old_backend)
    plt.close('all')
    sys.exit(exitcode)
开发者ID:dongxu-cug,项目名称:gimli,代码行数:60,代码来源:__init__.py


示例17: mpl_test_settings

def mpl_test_settings(request):
    from matplotlib.testing.decorators import _do_cleanup

    original_units_registry = matplotlib.units.registry.copy()
    original_settings = matplotlib.rcParams.copy()

    backend = None
    backend_marker = request.keywords.get('backend')
    if backend_marker is not None:
        assert len(backend_marker.args) == 1, \
            "Marker 'backend' must specify 1 backend."
        backend = backend_marker.args[0]
        prev_backend = matplotlib.get_backend()

    style = '_classic_test'  # Default of cleanup and image_comparison too.
    style_marker = request.keywords.get('style')
    if style_marker is not None:
        assert len(style_marker.args) == 1, \
            "Marker 'style' must specify 1 style."
        style = style_marker.args[0]

    matplotlib.testing.setup()
    if backend is not None:
        # This import must come after setup() so it doesn't load the default
        # backend prematurely.
        import matplotlib.pyplot as plt
        plt.switch_backend(backend)
    matplotlib.style.use(style)
    try:
        yield
    finally:
        if backend is not None:
            plt.switch_backend(prev_backend)
        _do_cleanup(original_units_registry,
                    original_settings)
开发者ID:adnanb59,项目名称:matplotlib,代码行数:35,代码来源:conftest.py


示例18: matplotlib_backend

def matplotlib_backend():
    """Figure out which matplotlib backend to use"""
    if platform.system().startswith('Linux'):
        if platform.linux_distribution()[0] == 'arch':
            plt.switch_backend('Qt4Agg')
    elif platform.system().startswith('Darwin'):
        plt.switch_backend('MacOSX')
开发者ID:roguePanda,项目名称:exoplanet-project,代码行数:7,代码来源:common.py


示例19: wrapped

        def wrapped(*args, **kwargs):
            orig_backend = plt.get_backend()
            plt.switch_backend('agg')
            mpl_setup()

            if pyplot_helpers.Gcf.figs:
                warnings.warn('Figures existed before running the %s %s test.'
                              ' All figures should be closed after they run. '
                              'They will be closed automatically now.' %
                              (mod_name, test_name))
                pyplot_helpers.Gcf.destroy_all()

            if MPL_VERSION >= '2':
                style_context = mpl.style.context
            else:
                @contextlib.contextmanager
                def style_context(style, after_reset=False):
                    yield

            with style_context(self.style):
                r = test_func(*args, **kwargs)

                fig_managers = pyplot_helpers.Gcf._activeQue
                figures = [manager.canvas.figure for manager in fig_managers]

                try:
                    self.run_figure_comparisons(figures, test_name=mod_name)
                finally:
                    for figure in figures:
                        pyplot_helpers.Gcf.destroy_fig(figure)
                    plt.switch_backend(orig_backend)
            return r
开发者ID:QuLogic,项目名称:cartopy,代码行数:32,代码来源:__init__.py


示例20: grafica_tasa_de_reservacion

def grafica_tasa_de_reservacion(request):
    
    # Recuperacion del diccionario para crear el grafico
    try:
        datos_ocupacion = request.GET.dict()
        datos_ocupacion = OrderedDict(sorted((k, float(v)) for k, v in datos_ocupacion.items()))     
        response = HttpResponse(content_type='image/png')
    except:
        return HttpResponse(status=400) # Bad request
    
    # Si el request no viene con algun diccionario
    if (not datos_ocupacion):
        return HttpResponse(status=400) # Bad request
    
    # Configuracion y creacion del grafico de barras con la biblioteca pyplot
    pyplot.switch_backend('Agg') # Para que no use Tk y aparezcan problemas con hilos
    pyplot.bar(range(len(datos_ocupacion)), datos_ocupacion.values(), hold = False, color = '#6495ed')
    pyplot.ylim([0,100])
    pyplot.title('Distribución de los porcentajes por fecha')
    pyplot.xticks(range(len(datos_ocupacion)), list(datos_ocupacion.keys()), rotation=20)
    pyplot.ylabel('Porcentaje (%)')
    pyplot.grid(True, 'major', 'both')
    pyplot.savefig(response, format='png') # Guarda la imagen creada en el HttpResponse creado
    pyplot.close()
    
    return response
开发者ID:Arleyn,项目名称:Sage-Edwin,代码行数:26,代码来源:views.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python pyplot.table函数代码示例发布时间:2022-05-27
下一篇:
Python pyplot.suptitle函数代码示例发布时间: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