本文整理汇总了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)
示例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)
示例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)
示例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)
示例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)
示例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)
示例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
示例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)
示例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
示例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)
示例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
示例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)
示例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)
示例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()