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


Python pyplot.switch_backend方法代碼示例

本文整理匯總了Python中matplotlib.pyplot.switch_backend方法的典型用法代碼示例。如果您正苦於以下問題:Python pyplot.switch_backend方法的具體用法?Python pyplot.switch_backend怎麽用?Python pyplot.switch_backend使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在matplotlib.pyplot的用法示例。


在下文中一共展示了pyplot.switch_backend方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: plotCM

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import switch_backend [as 別名]
def plotCM(classes, matrix, savname):
    """classes: a list of class names"""
    # Normalize by row
    matrix = matrix.astype(np.float)
    linesum = matrix.sum(1)
    linesum = np.dot(linesum.reshape(-1, 1), np.ones((1, matrix.shape[1])))
    matrix /= linesum
    # plot
    plt.switch_backend('agg')
    fig = plt.figure()
    ax = fig.add_subplot(111)
    cax = ax.matshow(matrix)
    fig.colorbar(cax)
    ax.xaxis.set_major_locator(MultipleLocator(1))
    ax.yaxis.set_major_locator(MultipleLocator(1))
    for i in range(matrix.shape[0]):
        ax.text(i, i, str('%.2f' % (matrix[i, i] * 100)), va='center', ha='center')
    ax.set_xticklabels([''] + classes, rotation=90)
    ax.set_yticklabels([''] + classes)
    plt.savefig(savname) 
開發者ID:MingtaoGuo,項目名稱:Chinese-Character-and-Calligraphic-Image-Processing,代碼行數:22,代碼來源:plot_confusion_matrix.py

示例2: __getitem__

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import switch_backend [as 別名]
def __getitem__(self, key):
        if key in _deprecated_map:
            version, alt_key, alt_val, inverse_alt = _deprecated_map[key]
            cbook.warn_deprecated(
                version, name=key, obj_type="rcparam", alternative=alt_key)
            return inverse_alt(dict.__getitem__(self, alt_key))

        elif key in _deprecated_ignore_map:
            version, alt_key = _deprecated_ignore_map[key]
            cbook.warn_deprecated(
                version, name=key, obj_type="rcparam", alternative=alt_key)
            return dict.__getitem__(self, alt_key) if alt_key else None

        elif key == 'examples.directory':
            cbook.warn_deprecated(
                "3.0", name=key, obj_type="rcparam", addendum="In the future, "
                "examples will be found relative to the 'datapath' directory.")

        elif key == "backend":
            val = dict.__getitem__(self, key)
            if val is rcsetup._auto_backend_sentinel:
                from matplotlib import pyplot as plt
                plt.switch_backend(rcsetup._auto_backend_sentinel)

        return dict.__getitem__(self, key) 
開發者ID:PacktPublishing,項目名稱:Mastering-Elasticsearch-7.0,代碼行數:27,代碼來源:__init__.py

示例3: test_fig_close

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import switch_backend [as 別名]
def test_fig_close():
    # force switch to the Qt4 backend
    plt.switch_backend('Qt4Agg')

    #save the state of Gcf.figs
    init_figs = copy.copy(Gcf.figs)

    # make a figure using pyplot interface
    fig = plt.figure()

    # simulate user clicking the close button by reaching in
    # and calling close on the underlying Qt object
    fig.canvas.manager.window.close()

    # assert that we have removed the reference to the FigureManager
    # that got added by plt.figure()
    assert(init_figs == Gcf.figs) 
開發者ID:miloharper,項目名稱:neural-network-animation,代碼行數:19,代碼來源:test_backend_qt4.py

示例4: assert_correct_key

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import switch_backend [as 別名]
def assert_correct_key(qt_key, qt_mods, answer):
    """
    Make a figure
    Send a key_press_event event (using non-public, qt4 backend specific api)
    Catch the event
    Assert sent and caught keys are the same
    """
    plt.switch_backend('Qt4Agg')
    qt_canvas = plt.figure().canvas

    event = mock.Mock()
    event.isAutoRepeat.return_value = False
    event.key.return_value = qt_key
    event.modifiers.return_value = qt_mods

    def receive(event):
        assert event.key == answer

    qt_canvas.mpl_connect('key_press_event', receive)
    qt_canvas.keyPressEvent(event) 
開發者ID:miloharper,項目名稱:neural-network-animation,代碼行數:22,代碼來源:test_backend_qt4.py

示例5: test_fig_close

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import switch_backend [as 別名]
def test_fig_close():
    # force switch to the Qt4 backend
    plt.switch_backend('Qt5Agg')

    #save the state of Gcf.figs
    init_figs = copy.copy(Gcf.figs)

    # make a figure using pyplot interface
    fig = plt.figure()

    # simulate user clicking the close button by reaching in
    # and calling close on the underlying Qt object
    fig.canvas.manager.window.close()

    # assert that we have removed the reference to the FigureManager
    # that got added by plt.figure()
    assert(init_figs == Gcf.figs) 
開發者ID:miloharper,項目名稱:neural-network-animation,代碼行數:19,代碼來源:test_backend_qt5.py

示例6: assert_correct_key

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import switch_backend [as 別名]
def assert_correct_key(qt_key, qt_mods, answer):
    """
    Make a figure
    Send a key_press_event event (using non-public, qt4 backend specific api)
    Catch the event
    Assert sent and caught keys are the same
    """
    plt.switch_backend('Qt5Agg')
    qt_canvas = plt.figure().canvas

    event = mock.Mock()
    event.isAutoRepeat.return_value = False
    event.key.return_value = qt_key
    event.modifiers.return_value = qt_mods

    def receive(event):
        assert event.key == answer

    qt_canvas.mpl_connect('key_press_event', receive)
    qt_canvas.keyPressEvent(event) 
開發者ID:miloharper,項目名稱:neural-network-animation,代碼行數:22,代碼來源:test_backend_qt5.py

示例7: __getitem__

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import switch_backend [as 別名]
def __getitem__(self, key):
        if key in _deprecated_map:
            version, alt_key, alt_val, inverse_alt = _deprecated_map[key]
            cbook.warn_deprecated(
                version, key, obj_type="rcparam", alternative=alt_key)
            return inverse_alt(dict.__getitem__(self, alt_key))

        elif key in _deprecated_ignore_map:
            version, alt_key = _deprecated_ignore_map[key]
            cbook.warn_deprecated(
                version, key, obj_type="rcparam", alternative=alt_key)
            return dict.__getitem__(self, alt_key) if alt_key else None

        elif key == 'examples.directory':
            cbook.warn_deprecated(
                "3.0", "{} is deprecated; in the future, examples will be "
                "found relative to the 'datapath' directory.".format(key))

        elif key == "backend":
            val = dict.__getitem__(self, key)
            if val is rcsetup._auto_backend_sentinel:
                from matplotlib import pyplot as plt
                plt.switch_backend(rcsetup._auto_backend_sentinel)

        return dict.__getitem__(self, key) 
開發者ID:Relph1119,項目名稱:GraphicDesignPatternByPython,代碼行數:27,代碼來源:__init__.py

示例8: switch_backend

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import switch_backend [as 別名]
def switch_backend(backend):

    def switch_backend_decorator(func):

        @functools.wraps(func)
        def backend_switcher(*args, **kwargs):
            try:
                prev_backend = mpl.get_backend()
                matplotlib.testing.setup()
                plt.switch_backend(backend)
                return func(*args, **kwargs)
            finally:
                plt.switch_backend(prev_backend)

        return backend_switcher

    return switch_backend_decorator 
開發者ID:Relph1119,項目名稱:GraphicDesignPatternByPython,代碼行數:19,代碼來源:decorators.py

示例9: log_matrix

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import switch_backend [as 別名]
def log_matrix(writer, mat, name, epoch, fig_size=(8, 6), dpi=200):
    """Save an image of a matrix to disk.

    Args:
        - writer    :  A file writer.
        - mat       :  The matrix to write.
        - name      :  Name of the file to save.
        - epoch     :  Epoch number.
        - fig_size  :  Size to of the figure to save.
        - dpi       :  Resolution.
    """
    plt.switch_backend("agg")
    fig = plt.figure(figsize=fig_size, dpi=dpi)
    mat = mat.cpu().detach().numpy()
    if mat.ndim == 1:
        mat = mat[:, np.newaxis]
    plt.imshow(mat, cmap=plt.get_cmap("BuPu"))
    cbar = plt.colorbar()
    cbar.solids.set_edgecolor("face")

    plt.tight_layout()
    fig.canvas.draw()
    writer.add_image(name, tensorboardX.utils.figure_to_image(fig), epoch) 
開發者ID:RexYing,項目名稱:gnn-model-explainer,代碼行數:25,代碼來源:io_utils.py

示例10: log_assignment

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import switch_backend [as 別名]
def log_assignment(assign_tensor, writer, epoch, batch_idx):
    plt.switch_backend("agg")
    fig = plt.figure(figsize=(8, 6), dpi=300)

    # has to be smaller than args.batch_size
    for i in range(len(batch_idx)):
        plt.subplot(2, 2, i + 1)
        plt.imshow(
            assign_tensor.cpu().data.numpy()[batch_idx[i]], cmap=plt.get_cmap("BuPu")
        )
        cbar = plt.colorbar()
        cbar.solids.set_edgecolor("face")
    plt.tight_layout()
    fig.canvas.draw()

    data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep="")
    data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
    writer.add_image("assignment", data, epoch)

# TODO: unify log_graph and log_graph2 
開發者ID:RexYing,項目名稱:gnn-model-explainer,代碼行數:22,代碼來源:io_utils.py

示例11: save_height_colormap

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import switch_backend [as 別名]
def save_height_colormap(self, filename, data, cmap='jet'):
        import matplotlib.pyplot as plt
        plt.switch_backend('agg')
        dpi = 80
        data = data[0,:,:]
        height, width = data.shape 
        figsize = width / float(dpi), height / float(dpi)
        # change string
        if 'output' in filename:
            filename = filename.replace('output_h', 'cmap_output_h')
        else:
            filename = filename.replace('target_h', 'cmap_target_h')
        fig = plt.figure(figsize=figsize)
        ax = fig.add_axes([0, 0, 1, 1])
        ax.axis('off')
        cax = ax.imshow(data, vmax=255, vmin=0, aspect='auto', interpolation='spline16', cmap=cmap)
        ax.set(xlim=[0, width], ylim=[height, 0], aspect=1)

        fig.savefig(filename, dpi=dpi) 
開發者ID:marcelampc,項目名稱:aerial_mtl,代碼行數:21,代碼來源:test_model_raster_isprs.py

示例12: save_height_colormap

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import switch_backend [as 別名]
def save_height_colormap(self, filename, data, cmap='jet'):
        import matplotlib.pyplot as plt
        plt.switch_backend('agg')
        dpi = 80
        data = data[0,:,:]
        height, width = data.shape 
        figsize = width / float(dpi), height / float(dpi)
        # change string
        if 'output' in filename:
            filename = filename.replace('merged_output', 'cmap_merged_output')
        else:
            filename = filename.replace('merged_target', 'cmap_merged_target')
        fig = plt.figure(figsize=figsize)
        ax = fig.add_axes([0, 0, 1, 1])
        ax.axis('off')
        cax = ax.imshow(data, vmax=30, vmin=0, aspect='auto', interpolation='spline16', cmap=cmap)
        ax.set(xlim=[0, width], ylim=[height, 0], aspect=1)

        fig.savefig(filename, dpi=dpi)
        del fig, data 
開發者ID:marcelampc,項目名稱:aerial_mtl,代碼行數:22,代碼來源:test_model_raster.py

示例13: test_plot_state_histogram

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import switch_backend [as 別名]
def test_plot_state_histogram():
    pl.switch_backend('PDF')
    simulator = cirq.Simulator()

    q0 = GridQubit(0, 0)
    q1 = GridQubit(1, 0)
    circuit = cirq.Circuit()
    circuit.append([cirq.X(q0), cirq.X(q1)])
    circuit.append([cirq.measure(q0, key='q0'), cirq.measure(q1, key='q1')])
    result = simulator.run(program=circuit,
                           repetitions=5)

    values_plotted = visualize.plot_state_histogram(result)
    expected_values = [0., 0., 0., 5.]

    np.testing.assert_equal(values_plotted, expected_values) 
開發者ID:quantumlib,項目名稱:Cirq,代碼行數:18,代碼來源:visualize_test.py

示例14: log_assignment

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import switch_backend [as 別名]
def log_assignment(assign_tensor, writer, epoch, batch_idx):
    plt.switch_backend('agg')
    fig = plt.figure(figsize=(8,6), dpi=300)

    # has to be smaller than args.batch_size
    for i in range(len(batch_idx)):
        plt.subplot(2, 2, i+1)
        plt.imshow(assign_tensor.cpu().data.numpy()[batch_idx[i]], cmap=plt.get_cmap('BuPu'))
        cbar = plt.colorbar()
        cbar.solids.set_edgecolor("face")
    plt.tight_layout()
    fig.canvas.draw()

    #data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
    #data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
    data = tensorboardX.utils.figure_to_image(fig)
    writer.add_image('assignment', data, epoch) 
開發者ID:RexYing,項目名稱:diffpool,代碼行數:19,代碼來源:train.py

示例15: plot

# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import switch_backend [as 別名]
def plot(self, min_val=-10, max_val=10, step_size=0.1, figsize=(10, 5), xlabel=None, ylabel='Probability', xticks=None, yticks=None, log_xscale=False, log_yscale=False, file_name=None, show=True, fig=None, *args, **kwargs):
        if fig is None:
            if not show:
                mpl.rcParams['axes.unicode_minus'] = False
                plt.switch_backend('agg')
            fig = plt.figure(figsize=figsize)
            fig.tight_layout()
        xvals = np.arange(min_val, max_val, step_size)
        plt.plot(xvals, [torch.exp(self.log_prob(x)) for x in xvals], *args, **kwargs)
        if log_xscale:
            plt.xscale('log')
        if log_yscale:
            plt.yscale('log', nonposy='clip')
        if xticks is not None:
            plt.xticks(xticks)
        if yticks is not None:
            plt.xticks(yticks)
        # if xlabel is None:
        #     xlabel = self.name
        plt.xlabel(xlabel)
        plt.ylabel(ylabel)
        if file_name is not None:
            plt.savefig(file_name)
        if show:
            plt.show() 
開發者ID:pyprob,項目名稱:pyprob,代碼行數:27,代碼來源:distribution.py


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