Python matplotlib.pyplot.switch_backend() Examples
The following are 30
code examples of matplotlib.pyplot.switch_backend().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
matplotlib.pyplot
, or try the search function
.
Example #1
Source File: io_utils.py From gnn-model-explainer with Apache License 2.0 | 6 votes |
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)
Example #2
Source File: test_backend_qt5.py From ImageFusion with MIT License | 6 votes |
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)
Example #3
Source File: __init__.py From GraphicDesignPatternByPython with MIT License | 6 votes |
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)
Example #4
Source File: test_backend_qt5.py From neural-network-animation with MIT License | 6 votes |
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)
Example #5
Source File: test_backend_qt5.py From neural-network-animation with MIT License | 6 votes |
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)
Example #6
Source File: test_backend_qt4.py From neural-network-animation with MIT License | 6 votes |
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)
Example #7
Source File: test_backend_qt4.py From neural-network-animation with MIT License | 6 votes |
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)
Example #8
Source File: test_model_raster_isprs.py From aerial_mtl with BSD 3-Clause "New" or "Revised" License | 6 votes |
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)
Example #9
Source File: test_model_raster.py From aerial_mtl with BSD 3-Clause "New" or "Revised" License | 6 votes |
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
Example #10
Source File: test_backend_qt5.py From ImageFusion with MIT License | 6 votes |
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)
Example #11
Source File: test_backend_qt4.py From ImageFusion with MIT License | 6 votes |
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)
Example #12
Source File: test_backend_qt4.py From ImageFusion with MIT License | 6 votes |
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)
Example #13
Source File: decorators.py From GraphicDesignPatternByPython with MIT License | 6 votes |
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
Example #14
Source File: static.py From PyChemia with MIT License | 6 votes |
def plot(self, figname='static_calculation.pdf'): if not self.finished: print('The task is not finished') return import matplotlib.pyplot as plt plt.switch_backend('agg') plt.figure(figsize=(8, 6)) plt.subplots_adjust(left=0.09, bottom=0.08, right=0.95, top=0.95, wspace=None, hspace=None) data = np.array(self.output['energies']) plt.plot(data[:, 1], data[:, 2], 'b.-') plt.xlabel('SCF cycle') plt.ylabel('Energy [eV]') a = plt.axes([.6, .6, .3, .3], axisbg='0.9') a.semilogy(data[:, 1], data[:, 2] - np.min(data[:, 2])) a.set_title('min energy %7.3f eV' % np.min(data[:, 2])) if figname is not None: plt.savefig(figname) return plt.gcf()
Example #15
Source File: visualize_test.py From Cirq with Apache License 2.0 | 6 votes |
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)
Example #16
Source File: __init__.py From Mastering-Elasticsearch-7.0 with MIT License | 6 votes |
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)
Example #17
Source File: static.py From PyChemia with MIT License | 6 votes |
def plot(self, figname='static_calculation.pdf'): if not self.finished: print('The task is not finished') return import matplotlib.pyplot as plt plt.switch_backend('agg') plt.figure(figsize=(8, 6)) plt.subplots_adjust(left=0.09, bottom=0.08, right=0.95, top=0.95, wspace=None, hspace=None) data = np.array(self.output['energies']) plt.plot(data[:, 1], data[:, 2], 'b.-') plt.xlabel('SCF cycle') plt.ylabel('Energy [eV]') a = plt.axes([.6, .6, .3, .3], axisbg='0.9') a.semilogy(data[:, 1], data[:, 2] - np.min(data[:, 2])) a.set_title('min energy %7.3f eV' % np.min(data[:, 2])) if figname is not None: plt.savefig(figname) return plt.gcf()
Example #18
Source File: __init__.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 6 votes |
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)
Example #19
Source File: train.py From diffpool with MIT License | 6 votes |
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)
Example #20
Source File: decorators.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 6 votes |
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
Example #21
Source File: test_window.py From pytomo3d with GNU Lesser General Public License v3.0 | 6 votes |
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.
Example #22
Source File: test_adjoint_source.py From pytomo3d with GNU Lesser General Public License v3.0 | 6 votes |
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
Example #23
Source File: distribution.py From pyprob with BSD 2-Clause "Simplified" License | 6 votes |
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()
Example #24
Source File: io_utils.py From gnn-model-explainer with Apache License 2.0 | 6 votes |
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
Example #25
Source File: plot_confusion_matrix.py From Chinese-Character-and-Calligraphic-Image-Processing with MIT License | 6 votes |
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)
Example #26
Source File: conftest.py From plotnine with GNU General Public License v2.0 | 5 votes |
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())
Example #27
Source File: example_test.py From Cirq with Apache License 2.0 | 5 votes |
def test_gate_compilation_example(): plt.switch_backend('agg') example.main(samples=10, max_infidelity=0.3)
Example #28
Source File: empirical.py From pyprob with BSD 2-Clause "Simplified" License | 5 votes |
def plot_histogram(self, figsize=(10, 5), xlabel=None, ylabel='Frequency', xticks=None, yticks=None, log_xscale=False, log_yscale=False, file_name=None, show=True, density=1, 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() values = self.values_numpy() weights = self.weights_numpy() plt.hist(values, weights=weights, density=density, *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()
Example #29
Source File: test_model_raster.py From aerial_mtl with BSD 3-Clause "New" or "Revised" License | 5 votes |
def save_raster_images_semantics(self, input, output, target, semantics, meta_data, shape, index, phase='train', out_type='png'): from dataloader.dataset_raster import sliding_window self.save_raster_images(input, output, target, meta_data[0], shape, index, phase) del input, output, target import gc gc.collect() filename = '{}/semantics/semantics_{:04}.tif'.format(self.save_samples_path, index) if self.opt.reconstruction_method == 'gaussian': semantics = np.argmax(semantics, axis=0) semantics = np.array(semantics, dtype=np.uint8) sem_patch = np.expand_dims(np.array(Image.fromarray(semantics, mode='P').resize(shape, Image.NEAREST)), axis=0) del semantics import rasterio with rasterio.open(filename, "w", **meta_data[1]) as dest: if dest.write(sem_patch) == False: print('Couldnt save image, sorry') # base_stride /= 2 del sem_patch # 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 # filename = filename.replace('output_', 'cmap_output_') # 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)
Example #30
Source File: test_backend_pgf.py From ImageFusion with MIT License | 5 votes |
def switch_backend(backend): def switch_backend_decorator(func): def backend_switcher(*args, **kwargs): try: prev_backend = mpl.get_backend() mpl.rcdefaults() plt.switch_backend(backend) result = func(*args, **kwargs) finally: plt.switch_backend(prev_backend) return result return nose.tools.make_decorator(func)(backend_switcher) return switch_backend_decorator