本文整理汇总了Python中matplotlib.use方法的典型用法代码示例。如果您正苦于以下问题:Python matplotlib.use方法的具体用法?Python matplotlib.use怎么用?Python matplotlib.use使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib
的用法示例。
在下文中一共展示了matplotlib.use方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: plot_coordinates
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import use [as 别名]
def plot_coordinates(coordinates, plot_path, markers, label_names, fig_num):
matplotlib.use('svg')
import matplotlib.pyplot as plt
plt.figure(fig_num)
for i in range(len(markers) - 1):
plt.scatter(x=coordinates[markers[i]:markers[i + 1], 0],
y=coordinates[markers[i]:markers[i + 1], 1],
marker=plot_markers[i % len(plot_markers)],
c=colors[i % len(colors)],
label=label_names[i], alpha=0.75)
plt.legend(loc='upper right', fontsize='x-large')
plt.axis('off')
plt.savefig(fname=plot_path, format="svg", bbox_inches='tight', transparent=True)
plt.close()
示例2: getFreeId
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import use [as 别名]
def getFreeId():
import pynvml
pynvml.nvmlInit()
def getFreeRatio(id):
handle = pynvml.nvmlDeviceGetHandleByIndex(id)
use = pynvml.nvmlDeviceGetUtilizationRates(handle)
ratio = 0.5*(float(use.gpu+float(use.memory)))
return ratio
deviceCount = pynvml.nvmlDeviceGetCount()
available = []
for i in range(deviceCount):
if getFreeRatio(i)<70:
available.append(i)
gpus = ''
for g in available:
gpus = gpus+str(g)+','
gpus = gpus[:-1]
return gpus
示例3: set_device
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import use [as 别名]
def set_device(use_gpu, multi_gpu, _log):
# Decide which device to use.
if use_gpu and not torch.cuda.is_available():
raise RuntimeError('use_gpu is True but CUDA is not available')
if use_gpu:
device = torch.device('cuda')
torch.set_default_tensor_type('torch.cuda.FloatTensor')
else:
device = torch.device('cpu')
if multi_gpu and torch.cuda.device_count() == 1:
raise RuntimeError('Multiple GPU training requested, but only one GPU is available.')
if multi_gpu:
_log.info('Using all {} GPUs available'.format(torch.cuda.device_count()))
return device
示例4: hzfunc
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import use [as 别名]
def hzfunc(self,label):
ax = self.hzdict[label]
num = int(label.replace("plot ",""))
#print "Selected axis number:", num
#global mainnum
self.mainnum = num
# drawtype is 'box' or 'line' or 'none'
toggle_selector.RS = RectangleSelector(ax, self.line_select_callback,
drawtype='box', useblit=True,
button=[1,3], # don't use middle button
minspanx=5, minspany=5,
spancoords='pixels',
rectprops = dict(facecolor='red', edgecolor = 'black', alpha=0.2, fill=True))
#plt.connect('key_press_event', toggle_selector)
plt.draw()
示例5: validation
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import use [as 别名]
def validation(self, sess, cells_no, exp_folder, train_step):
"""
Method that initiates some validation steps of the current model.
Parameters
----------
sess : Session
The TF Session in use.
cells_no : int
Number of cells to use for the validation step.
exp_folder : str
Path to the job folder in which the outputs will be saved.
train_step : int
Index of the current training step.
Returns
-------
"""
print("Find tSNE embedding for the generated and the validation cells")
self.generate_tSNE_image(sess, cells_no, exp_folder, train_step)
示例6: evaluate_pi
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import use [as 别名]
def evaluate_pi(q, task):
# use Monte Carlo method to estimate the state value
runs = 1000
returns = []
for r in range(runs):
rewards = 0
state = 0
while state < task.n_states:
action = argmax(q[state])
state, r = task.step(state, action)
rewards += r
returns.append(rewards)
return np.mean(returns)
# perform expected update from a uniform state-action distribution of the MDP @task
# evaluate the learned q value every @eval_interval steps
开发者ID:ShangtongZhang,项目名称:reinforcement-learning-an-introduction,代码行数:18,代码来源:trajectory_sampling.py
示例7: _twopop_IM
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import use [as 别名]
def _twopop_IM(
engine_id, out_dir, seed,
NA=1000, N1=500, N2=5000, T=1000, M12=0, M21=0, pulse=None, samples=None,
**sim_kwargs):
species = stdpopsim.get_species("AraTha")
contig = species.get_contig("chr5", length_multiplier=0.01) # ~270 kb
contig = irradiate(contig)
model = stdpopsim.IsolationWithMigration(
NA=NA, N1=N1, N2=N2, T=T, M12=M12, M21=M21)
if pulse is not None:
model.demographic_events.append(pulse)
model.demographic_events.sort(key=lambda x: x.time)
# XXX: AraTha has species.generation_time == 1, but there is the potential
# for this to mask bugs related to generation_time scaling, so we use 3 here.
model.generation_time = 3
if samples is None:
samples = model.get_samples(50, 50, 0)
engine = stdpopsim.get_engine(engine_id)
t0 = time.perf_counter()
ts = engine.simulate(model, contig, samples, seed=seed, **sim_kwargs)
t1 = time.perf_counter()
out_file = out_dir / f"{seed}.trees"
ts.dump(out_file)
return out_file, t1 - t0
示例8: _create_solutions_model
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import use [as 别名]
def _create_solutions_model(self):
"""
Create pymc model components for true concentrations of source receptor and ligand solutions.
Populates the following fields:
* parameter_names['concentrations'] : parameters associated with true concentrations of receptor and ligand solutions
"""
# Determine solutions in use in plate
solutions_in_use = set()
for well in self.wells:
for shortname in well.properties['contents']:
solutions_in_use.add(shortname)
print('Solutions in use: %s' % str(solutions_in_use))
# Retain only solutions that appear in the plate
self.solutions = { shortname : self.solutions[shortname] for shortname in solutions_in_use }
self.parameter_names['solution concentrations'] = list()
for solution in self.solutions.values():
if solution.species is None:
continue # skip buffers or pure solvents
name = 'log concentration of %s' % solution.shortname
self.model[name] = LogNormalWrapper(name, mean=solution.concentration.to_base_units().m, stddev=solution.uncertainty.to_base_units().m)
self.parameter_names['solution concentrations'].append(name)
示例9: chunkIt
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import use [as 别名]
def chunkIt(seq, num):
"""
This comes from https://stackoverflow.com/questions/2130016/splitting-a-list-into-n-parts-of-approximately-equal-length
I will use it to create a bunch of lists for sequential clustering
Args:
seq: The initial list for chunking
num: The number of items in each chunk
Return:
A chunked list with roughly equal numbers of elements
Author: Max Shawabkeh
"""
avg = len(seq) / float(num)
out = []
last = 0.0
while last < len(seq):
out.append(seq[int(last):int(last + avg)])
last += avg
return out
示例10: __generic_histo__
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import use [as 别名]
def __generic_histo__(self, vector, labels):
# This function just calls the appropriate plot function for our available
# interface. Same thing as generic_ci, but for a histogram.
if self.interface == 'text':
self.__terminal_histo__(vector, labels)
else:
try:
import matplotlib
matplotlib.use('TkAgg')
from matplotlib import pyplot as plt
plt.bar(list(range(0, np.array(vector).shape[0])), vector, linewidth=0, align='center', color='gold', tick_label=labels)
plt.show()
except:
print('Unable to import plotting interface. An X server ($DISPLAY) is required.')
self.__terminal_histo__(h5file, vector, labels)
return 1
示例11: __init__
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import use [as 别名]
def __init__(self, kaldi_root, hop=160, win=400, sr=16000,
num_mel_bins=40, num_ceps=13, der_order=2,
name='kaldimfcc'):
super(KaldiMFCC, self).__init__(kaldi_root=kaldi_root,
hop=hop, win=win, sr=sr)
self.num_mel_bins = num_mel_bins
self.num_ceps = num_ceps
self.der_order=der_order
cmd = "ark:| {}/src/featbin/compute-mfcc-feats --print-args=false "\
"--use-energy=false --snip-edges=false --num-ceps={} "\
"--frame-length={} --frame-shift={} "\
"--num-mel-bins={} --sample-frequency={} ark:- ark:- |"\
" {}/src/featbin/add-deltas --print-args=false "\
"--delta-order={} ark:- ark:- |"
self.cmd = cmd.format(self.kaldi_root, self.num_ceps,
self.frame_length, self.frame_shift,
self.num_mel_bins, self.sr, self.kaldi_root,
self.der_order)
self.name = name
示例12: plot_images
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import use [as 别名]
def plot_images(ax, images, shape, color = False):
# finally save to file
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
# flip 0 to 1
images = 1.0 - images
images = reshape_and_tile_images(images, shape, n_cols=len(images))
if color:
from matplotlib import cm
plt.imshow(images, cmap=cm.Greys_r, interpolation='nearest')
else:
plt.imshow(images, cmap='Greys')
ax.axis('off')
示例13: get_lat_lon_from_csv
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import use [as 别名]
def get_lat_lon_from_csv(csv_file, lats=[], lons=[]):
"""
Retrieves the last two rows of a CSV formatted file to use as latitude
and longitude.
Returns two lists (latitudes and longitudes).
Example CSV file:
119.80.39.54, Beijing, China, 39.9289, 116.3883
101.44.1.135, Shanghai, China, 31.0456, 121.3997
219.144.17.74, Xian, China, 34.2583, 108.9286
64.27.26.7, Los Angeles, United States, 34.053, -118.2642
"""
with contextlib.closing(csv_file):
reader = csv.reader(csv_file)
for row in reader:
lats.append(row[-2])
lons.append(row[-1])
return lats, lons
示例14: mpl_hist_arg
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import use [as 别名]
def mpl_hist_arg(value=True):
"""Find the appropriate `density` kwarg for our given matplotlib version.
This will determine if we should use `normed` or `density`. Additionally,
since this is a kwarg, the user can supply a value (True or False) that
they would like in the output dictionary.
Parameters
----------
value : bool, optional (default=True)
The boolean value of density/normed
Returns
-------
density_kwarg : dict
A dictionary containing the appropriate density kwarg for the
installed matplotlib version, mapped to the provided or default
value
"""
import matplotlib
density_kwarg = 'density' if matplotlib.__version__ >= '2.1.0'\
else 'normed'
return {density_kwarg: value}
示例15: pair_visual
# 需要导入模块: import matplotlib [as 别名]
# 或者: from matplotlib import use [as 别名]
def pair_visual(original, adversarial, figure=None):
"""
This function displays two images: the original and the adversarial sample
:param original: the original input
:param adversarial: the input after perterbations have been applied
:param figure: if we've already displayed images, use the same plot
:return: the matplot figure to reuse for future samples
"""
import matplotlib.pyplot as plt
# Squeeze the image to remove single-dimensional entries from array shape
original = np.squeeze(original)
adversarial = np.squeeze(adversarial)
# Ensure our inputs are of proper shape
assert(len(original.shape) == 2 or len(original.shape) == 3)
# To avoid creating figures per input sample, reuse the sample plot
if figure is None:
plt.ion()
figure = plt.figure()
figure.canvas.set_window_title('Cleverhans: Pair Visualization')
# Add the images to the plot
perterbations = adversarial - original
for index, image in enumerate((original, perterbations, adversarial)):
figure.add_subplot(1, 3, index + 1)
plt.axis('off')
# If the image is 2D, then we have 1 color channel
if len(image.shape) == 2:
plt.imshow(image, cmap='gray')
else:
plt.imshow(image)
# Give the plot some time to update
plt.pause(0.01)
# Draw the plot and return
plt.show()
return figure