本文整理汇总了Python中matplotlib.pyplot.switch_backend函数的典型用法代码示例。如果您正苦于以下问题:Python switch_backend函数的具体用法?Python switch_backend怎么用?Python switch_backend使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了switch_backend函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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()
示例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)
示例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)
示例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)
示例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')
示例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
示例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)
示例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)
示例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)
示例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)
示例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())
示例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()
示例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)
示例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)
示例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)