本文整理汇总了Python中matplotlib.pyplot.subplot方法的典型用法代码示例。如果您正苦于以下问题:Python pyplot.subplot方法的具体用法?Python pyplot.subplot怎么用?Python pyplot.subplot使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.pyplot
的用法示例。
在下文中一共展示了pyplot.subplot方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: demo_plot
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import subplot [as 别名]
def demo_plot():
audio = './data/esc10/audio/Dog/1-30226-A.ogg'
y, sr = librosa.load(audio, sr=44100)
y_ps = librosa.effects.pitch_shift(y, sr, n_steps=6) # n_steps控制音调变化尺度
y_ts = librosa.effects.time_stretch(y, rate=1.2) # rate控制时间维度的变换尺度
plt.subplot(311)
plt.plot(y)
plt.title('Original waveform')
plt.axis([0, 200000, -0.4, 0.4])
# plt.axis([88000, 94000, -0.4, 0.4])
plt.subplot(312)
plt.plot(y_ts)
plt.title('Time Stretch transformed waveform')
plt.axis([0, 200000, -0.4, 0.4])
plt.subplot(313)
plt.plot(y_ps)
plt.title('Pitch Shift transformed waveform')
plt.axis([0, 200000, -0.4, 0.4])
# plt.axis([88000, 94000, -0.4, 0.4])
plt.tight_layout()
plt.show()
示例2: show
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import subplot [as 别名]
def show(mnist, targets, ret):
target_ids = range(len(set(targets)))
colors = ['r', 'g', 'b', 'c', 'm', 'y', 'k', 'violet', 'orange', 'purple']
plt.figure(figsize=(12, 10))
ax = plt.subplot(aspect='equal')
for label in set(targets):
idx = np.where(np.array(targets) == label)[0]
plt.scatter(ret[idx, 0], ret[idx, 1], c=colors[label], label=label)
for i in range(0, len(targets), 250):
img = (mnist[i][0] * 0.3081 + 0.1307).numpy()[0]
img = OffsetImage(img, cmap=plt.cm.gray_r, zoom=0.5)
ax.add_artist(AnnotationBbox(img, ret[i]))
plt.legend()
plt.show()
示例3: plot_images
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import subplot [as 别名]
def plot_images(imgs, targets, paths=None, fname='images.jpg'):
# Plots training images overlaid with targets
imgs = imgs.cpu().numpy()
targets = targets.cpu().numpy()
# targets = targets[targets[:, 1] == 21] # plot only one class
fig = plt.figure(figsize=(10, 10))
bs, _, h, w = imgs.shape # batch size, _, height, width
bs = min(bs, 16) # limit plot to 16 images
ns = np.ceil(bs ** 0.5) # number of subplots
for i in range(bs):
boxes = xywh2xyxy(targets[targets[:, 0] == i, 2:6]).T
boxes[[0, 2]] *= w
boxes[[1, 3]] *= h
plt.subplot(ns, ns, i + 1).imshow(imgs[i].transpose(1, 2, 0))
plt.plot(boxes[[0, 2, 2, 0, 0]], boxes[[1, 1, 3, 3, 1]], '.-')
plt.axis('off')
if paths is not None:
s = Path(paths[i]).name
plt.title(s[:min(len(s), 40)], fontdict={'size': 8}) # limit to 40 characters
fig.tight_layout()
fig.savefig(fname, dpi=200)
plt.close()
示例4: plot_evolution_results
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import subplot [as 别名]
def plot_evolution_results(hyp): # from utils.utils import *; plot_evolution_results(hyp)
# Plot hyperparameter evolution results in evolve.txt
x = np.loadtxt('evolve.txt', ndmin=2)
f = fitness(x)
weights = (f - f.min()) ** 2 # for weighted results
fig = plt.figure(figsize=(12, 10))
matplotlib.rc('font', **{'size': 8})
for i, (k, v) in enumerate(hyp.items()):
y = x[:, i + 5]
# mu = (y * weights).sum() / weights.sum() # best weighted result
mu = y[f.argmax()] # best single result
plt.subplot(4, 5, i + 1)
plt.plot(mu, f.max(), 'o', markersize=10)
plt.plot(y, f, '.')
plt.title('%s = %.3g' % (k, mu), fontdict={'size': 9}) # limit to 40 characters
print('%15s: %.3g' % (k, mu))
fig.tight_layout()
plt.savefig('evolve.png', dpi=200)
示例5: plot_some_results
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import subplot [as 别名]
def plot_some_results(pred_fn, test_generator, n_images=10):
fig_ctr = 0
for data, seg in test_generator:
res = pred_fn(data)
for d, s, r in zip(data, seg, res):
plt.figure(figsize=(12, 6))
plt.subplot(1, 3, 1)
plt.imshow(d.transpose(1,2,0))
plt.title("input patch")
plt.subplot(1, 3, 2)
plt.imshow(s[0])
plt.title("ground truth")
plt.subplot(1, 3, 3)
plt.imshow(r)
plt.title("segmentation")
plt.savefig("road_segmentation_result_%03.0f.png"%fig_ctr)
plt.close()
fig_ctr += 1
if fig_ctr > n_images:
break
示例6: __init__
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import subplot [as 别名]
def __init__(self, cf):
self.file_name = cf.plot_dir + '/monitor_{}'.format(cf.fold)
self.exp_name = cf.fold_dir
self.do_validation = cf.do_validation
self.separate_values_dict = cf.assign_values_to_extra_figure
self.figure_list = []
for n in range(cf.n_monitoring_figures):
self.figure_list.append(plt.figure(figsize=(10, 6)))
self.figure_list[-1].ax1 = plt.subplot(111)
self.figure_list[-1].ax1.set_xlabel('epochs')
self.figure_list[-1].ax1.set_ylabel('loss / metrics')
self.figure_list[-1].ax1.set_xlim(0, cf.num_epochs)
self.figure_list[-1].ax1.grid()
self.figure_list[0].ax1.set_ylim(0, 1.5)
self.color_palette = ['b', 'c', 'r', 'purple', 'm', 'y', 'k', 'tab:gray']
示例7: ShowPlots
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import subplot [as 别名]
def ShowPlots(subplot=False):
for log_ind, path in enumerate(FLAGS.path.split(":")):
log = Log(path)
if subplot:
plt.subplot(len(FLAGS.path.split(":")), 1, log_ind + 1)
for index in FLAGS.index.split(","):
index = int(index)
for attr in ["pred_acc", "parse_acc", "total_cost", "xent_cost", "l2_cost", "action_cost"]:
if getattr(FLAGS, attr):
if "cost" in attr:
assert index == 0, "costs only associated with training log"
steps, val = zip(*[(l.step, getattr(l, attr)) for l in log.corpus[index] if l.step < FLAGS.iters])
dct = {}
for k, v in zip(steps, val):
dct[k] = max(v, dct[k]) if k in dct else v
steps, val = zip(*sorted(dct.iteritems()))
plt.plot(steps, val, label="Log%d:%s-%d" % (log_ind, attr, index))
plt.xlabel("No. of training iteration")
plt.ylabel(FLAGS.ylabel)
if FLAGS.legend:
plt.legend()
plt.show()
示例8: plot_mean_bootstrap_exponential_readme
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import subplot [as 别名]
def plot_mean_bootstrap_exponential_readme():
X = np.random.exponential(7, 4)
classical_samples = [np.mean(resample(X)) for _ in range(10000)]
posterior_samples = mean(X, 10000)
l, r = highest_density_interval(posterior_samples)
classical_l, classical_r = highest_density_interval(classical_samples)
plt.subplot(2, 1, 1)
plt.title('Bayesian Bootstrap of mean')
sns.distplot(posterior_samples, label='Bayesian Bootstrap Samples')
plt.plot([l, r], [0, 0], linewidth=5.0, marker='o', label='95% HDI')
plt.xlim(-1, 18)
plt.legend()
plt.subplot(2, 1, 2)
plt.title('Classical Bootstrap of mean')
sns.distplot(classical_samples, label='Classical Bootstrap Samples')
plt.plot([classical_l, classical_r], [0, 0], linewidth=5.0, marker='o', label='95% HDI')
plt.xlim(-1, 18)
plt.legend()
plt.savefig('readme_exponential.png', bbox_inches='tight')
示例9: plotNNFilter
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import subplot [as 别名]
def plotNNFilter(units, figure_id, interp='bilinear', colormap=cm.jet, colormap_lim=None):
plt.ion()
filters = units.shape[2]
n_columns = round(math.sqrt(filters))
n_rows = math.ceil(filters / n_columns) + 1
fig = plt.figure(figure_id, figsize=(n_rows*3,n_columns*3))
fig.clf()
for i in range(filters):
ax1 = plt.subplot(n_rows, n_columns, i+1)
plt.imshow(units[:,:,i].T, interpolation=interp, cmap=colormap)
plt.axis('on')
ax1.set_xticklabels([])
ax1.set_yticklabels([])
plt.colorbar()
if colormap_lim:
plt.clim(colormap_lim[0],colormap_lim[1])
plt.subplots_adjust(wspace=0, hspace=0)
plt.tight_layout()
# Epochs
示例10: plotNNFilter
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import subplot [as 别名]
def plotNNFilter(units, figure_id, interp='bilinear', colormap=cm.jet, colormap_lim=None):
plt.ion()
filters = units.shape[2]
n_columns = round(math.sqrt(filters))
n_rows = math.ceil(filters / n_columns) + 1
fig = plt.figure(figure_id, figsize=(n_rows*3,n_columns*3))
fig.clf()
for i in range(filters):
ax1 = plt.subplot(n_rows, n_columns, i+1)
plt.imshow(units[:,:,i].T, interpolation=interp, cmap=colormap)
plt.axis('on')
ax1.set_xticklabels([])
ax1.set_yticklabels([])
plt.colorbar()
if colormap_lim:
plt.clim(colormap_lim[0],colormap_lim[1])
plt.subplots_adjust(wspace=0, hspace=0)
plt.tight_layout()
# Load options
示例11: plotNNFilter
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import subplot [as 别名]
def plotNNFilter(units, figure_id, interp='bilinear', colormap=cm.jet, colormap_lim=None, title=''):
plt.ion()
filters = units.shape[2]
n_columns = round(math.sqrt(filters))
n_rows = math.ceil(filters / n_columns) + 1
fig = plt.figure(figure_id, figsize=(n_rows*3,n_columns*3))
fig.clf()
for i in range(filters):
ax1 = plt.subplot(n_rows, n_columns, i+1)
plt.imshow(units[:,:,i].T, interpolation=interp, cmap=colormap)
plt.axis('on')
ax1.set_xticklabels([])
ax1.set_yticklabels([])
plt.colorbar()
if colormap_lim:
plt.clim(colormap_lim[0],colormap_lim[1])
plt.subplots_adjust(wspace=0, hspace=0)
plt.tight_layout()
plt.suptitle(title)
示例12: display_images
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import subplot [as 别名]
def display_images(images, titles=None, cols=4, cmap=None, norm=None,
interpolation=None):
"""Display the given set of images, optionally with titles.
images: list or array of image tensors in HWC format.
titles: optional. A list of titles to display with each image.
cols: number of images per row
cmap: Optional. Color map to use. For example, "Blues".
norm: Optional. A Normalize instance to map values to colors.
interpolation: Optional. Image interpolation to use for display.
"""
titles = titles if titles is not None else [""] * len(images)
rows = len(images) // cols + 1
plt.figure(figsize=(14, 14 * rows // cols))
i = 1
for image, title in zip(images, titles):
plt.subplot(rows, cols, i)
plt.title(title, fontsize=9)
plt.axis('off')
plt.imshow(image.astype(np.uint8), cmap=cmap,
norm=norm, interpolation=interpolation)
i += 1
plt.show()
示例13: visualize_transform
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import subplot [as 别名]
def visualize_transform(
potential_or_samples, prior_sample, prior_density, transform=None, inverse_transform=None, samples=True, npts=100,
memory=100, device="cpu"
):
"""Produces visualization for the model density and samples from the model."""
plt.clf()
ax = plt.subplot(1, 3, 1, aspect="equal")
if samples:
plt_samples(potential_or_samples, ax, npts=npts)
else:
plt_potential_func(potential_or_samples, ax, npts=npts)
ax = plt.subplot(1, 3, 2, aspect="equal")
if inverse_transform is None:
plt_flow(prior_density, transform, ax, npts=npts, device=device)
else:
plt_flow_density(prior_density, inverse_transform, ax, npts=npts, memory=memory, device=device)
ax = plt.subplot(1, 3, 3, aspect="equal")
if transform is not None:
plt_flow_samples(prior_sample, transform, ax, npts=npts, memory=memory, device=device)
示例14: imsplot_tensor
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import subplot [as 别名]
def imsplot_tensor(*imgs_tensor):
"""
使用matplotlib.pyplot绘制多个tensor类型图片
图片尺寸应为(bn, c, h, w)
或是单个图片尺寸为(1, c, h, w)的序列
"""
count = min(8, len(imgs_tensor))
if(count==0): return
col = min(2, count)
row = count//col
if(count%col > 0):
row = row + 1
for i in range(count):
plt.subplot(row, col, i+1);imshow_tensor(imgs_tensor[i])
# 计算并存储参数当前值和平均值
示例15: draw_plots
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import subplot [as 别名]
def draw_plots(strategy, accu_x, accu_y, auc_x, auc_y):
"""Draws the plot
**Parameters**
* strategy
* accu_x (*list*)
* accu_y (*list*)
* auc_x (*list*)
* auc_y (*list*)
"""
plt.figure(1)
plt.subplot(211)
plt.plot(accu_x, accu_y, '-', label=strategy)
plt.legend(loc='best')
plt.title('Accuracy')
plt.subplot(212)
plt.plot(auc_x, auc_y, '-', label=strategy)
plt.legend(loc='best')
plt.title('AUC')