本文整理汇总了Python中matplotlib.pylab.subplot方法的典型用法代码示例。如果您正苦于以下问题:Python pylab.subplot方法的具体用法?Python pylab.subplot怎么用?Python pylab.subplot使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.pylab
的用法示例。
在下文中一共展示了pylab.subplot方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import subplot [as 别名]
def __init__(self, fig, gs, labels=None, limits=None):
self._fig = fig
self._gs = gridspec.GridSpecFromSubplotSpec(1, 1, subplot_spec=gs)
self._ax = plt.subplot(self._gs[0])
self._arrow = None
if labels:
if len(labels) == 2:
self._ax.set_xlabel(labels[0])
self._ax.set_ylabel(labels[1])
else:
raise ValueError("invalid labels %r" % labels)
if limits:
if len(limits) == 2 and \
len(limits[0]) == 2 and \
len(limits[1]) == 2:
self._ax.set_xlim([limits[0][0], limits[1][0]])
self._ax.set_ylim([limits[0][1], limits[1][1]])
else:
raise ValueError("invalid limits %r" % limits)
self._fig.canvas.draw()
self._fig.canvas.flush_events() # Fixes bug with Qt4Agg backend
示例2: __init__
# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import subplot [as 别名]
def __init__(self, fig, gs, format_strings=None, format_dicts=None, labels=None, xlabel=None, ylabel=None, yscale='linear'):
self._fig = fig
self._gs = gridspec.GridSpecFromSubplotSpec(1, 1, subplot_spec=gs)
self._ax = plt.subplot(self._gs[0])
self._labels = labels or []
self._format_strings = format_strings or []
self._format_dicts = format_dicts or []
self._ax.set_xlabel(xlabel or 'iteration')
self._ax.set_ylabel(ylabel or 'loss')
self._ax.set_yscale(yscale or 'linear')
self._ax.minorticks_on()
self._plots = []
self._fig.canvas.draw()
self._fig.canvas.flush_events() # Fixes bug with Qt4Agg backend
示例3: __init__
# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import subplot [as 别名]
def __init__(self, fig, gs, label='mean', color='black', alpha=1.0, min_itr=10):
self._fig = fig
self._gs = gridspec.GridSpecFromSubplotSpec(1, 1, subplot_spec=gs)
self._ax = plt.subplot(self._gs[0])
self._label = label
self._color = color
self._alpha = alpha
self._min_itr = min_itr
self._ts = np.empty((1, 0))
self._data_mean = np.empty((1, 0))
self._plots_mean = self._ax.plot([], [], '-x', markeredgewidth=1.0,
color=self._color, alpha=1.0, label=self._label)[0]
self._ax.set_xlim(0-0.5, self._min_itr+0.5)
self._ax.set_ylim(0, 1)
self._ax.minorticks_on()
self._ax.legend(loc='upper right', bbox_to_anchor=(1, 1))
self._init = False
self._fig.canvas.draw()
self._fig.canvas.flush_events() # Fixes bug with Qt4Agg backend
示例4: show_pred
# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import subplot [as 别名]
def show_pred(images, predictions, ground_truth):
# choose 10 indice from images and visualize them
indice = [np.random.randint(0, len(images)) for i in range(40)]
for i in range(0, 40):
plt.figure()
plt.subplot(1, 3, 1)
plt.tight_layout()
plt.title('deformed image')
plt.imshow(images[indice[i]])
plt.subplot(1, 3, 2)
plt.tight_layout()
plt.title('predicted mask')
plt.imshow(predictions[indice[i]])
plt.subplot(1, 3, 3)
plt.tight_layout()
plt.title('ground truth label')
plt.imshow(ground_truth[indice[i]])
plt.show()
# Load Data Science Bowl 2018 training dataset
示例5: viz_missing_docwordfreq_stats
# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import subplot [as 别名]
def viz_missing_docwordfreq_stats(DocWordFreq_emp, DocWordFreq_model):
from matplotlib import pylab
DocWordFreq_missing = np.maximum(DocWordFreq_emp - DocWordFreq_model, 0)
nnzEmp = count_num_nonzero(DocWordFreq_emp)
nnzMiss = count_num_nonzero(DocWordFreq_missing)
frac_nzMiss = nnzMiss / float(nnzEmp)
nzMissPerDoc = np.sum(DocWordFreq_missing > 0, axis=1)
CDF_nzMissPerDoc = np.sort(nzMissPerDoc)
nzMissPerWord = np.sum(DocWordFreq_missing > 0, axis=0)
CDF_nzMissPerWord = np.sort(nzMissPerWord)
pylab.subplot(1,2,1)
pylab.plot(CDF_nzMissPerDoc)
pylab.ylabel('Num Nonzero Entries in Doc')
pylab.xlabel('Document rank | frac= %.4f'% (frac_nzMiss))
pylab.subplot(1,2,2)
pylab.plot(CDF_nzMissPerWord)
pylab.ylabel('Num Nonzero Entries per Word')
pylab.xlabel('Word rank')
pylab.show(block=True)
示例6: __init__
# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import subplot [as 别名]
def __init__(self):
self.rewards = 10 * [np.nan]
self.rewards_bounds = [-10, 10]
self.last_success = None
plt.ion()
self._fig = plt.figure(
figsize=(9, 12), num='Spriteworld', facecolor='white')
gs = gridspec.GridSpec(2, 1, height_ratios=[3, 1])
self._ax_image = plt.subplot(gs[0])
self._ax_image.axis('off')
self._ax_scalar = plt.subplot(gs[1])
self._ax_scalar.spines['right'].set_visible(False)
self._ax_scalar.spines['top'].set_visible(False)
self._ax_scalar.xaxis.set_ticks_position('bottom')
self._ax_scalar.yaxis.set_ticks_position('left')
self._setup_callbacks()
示例7: save_state_images
# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import subplot [as 别名]
def save_state_images(frame_idx, states, net, device="cpu", max_states=200):
ofs = 0
p = np.arange(Vmin, Vmax + DELTA_Z, DELTA_Z)
for batch in np.array_split(states, 64):
states_v = torch.tensor(batch).to(device)
action_prob = net.apply_softmax(net(states_v)).data.cpu().numpy()
batch_size, num_actions, _ = action_prob.shape
for batch_idx in range(batch_size):
plt.clf()
for action_idx in range(num_actions):
plt.subplot(num_actions, 1, action_idx+1)
plt.bar(p, action_prob[batch_idx, action_idx], width=0.5)
plt.savefig("states/%05d_%08d.png" % (ofs + batch_idx, frame_idx))
ofs += batch_size
if ofs >= max_states:
break
示例8: save_transition_images
# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import subplot [as 别名]
def save_transition_images(batch_size, predicted, projected, next_distr, dones, rewards, save_prefix):
for batch_idx in range(batch_size):
is_done = dones[batch_idx]
reward = rewards[batch_idx]
plt.clf()
p = np.arange(Vmin, Vmax + DELTA_Z, DELTA_Z)
plt.subplot(3, 1, 1)
plt.bar(p, predicted[batch_idx], width=0.5)
plt.title("Predicted")
plt.subplot(3, 1, 2)
plt.bar(p, projected[batch_idx], width=0.5)
plt.title("Projected")
plt.subplot(3, 1, 3)
plt.bar(p, next_distr[batch_idx], width=0.5)
plt.title("Next state")
suffix = ""
if reward != 0.0:
suffix = suffix + "_%.0f" % reward
if is_done:
suffix = suffix + "_done"
plt.savefig("%s_%02d%s.png" % (save_prefix, batch_idx, suffix))
示例9: plot_valdata
# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import subplot [as 别名]
def plot_valdata(x_val_cuda, knobs_val_cuda, y_val_cuda, y_val_hat_cuda, effect, \
epoch, loss_val, file_prefix='val_data', num_plots=50, target_size=None):
x_size = len(x_val_cuda.data.cpu().numpy()[0])
if target_size is None:
y_size = len(y_val_cuda.data.cpu().numpy()[0])
else:
y_size = target_size
t_small = range(x_size-y_size, x_size)
for plot_i in range(0, num_plots):
x_val = x_val_cuda.data.cpu().numpy()
knobs_w = effect.knobs_wc( knobs_val_cuda.data.cpu().numpy()[plot_i,:] )
plt.figure(plot_i,figsize=(6,8))
titlestr = f'{effect.name} Val data, epoch {epoch+1}, loss_val = {loss_val.item():.3e}\n'
for i in range(len(effect.knob_names)):
titlestr += f'{effect.knob_names[i]} = {knobs_w[i]:.2f}'
if i < len(effect.knob_names)-1: titlestr += ', '
plt.suptitle(titlestr)
plt.subplot(3, 1, 1)
plt.plot(x_val[plot_i, :], 'b', label='Input')
plt.ylim(-1,1)
plt.xlim(0,x_size)
plt.legend()
plt.subplot(3, 1, 2)
y_val = y_val_cuda.data.cpu().numpy()
plt.plot(t_small, y_val[plot_i, -y_size:], 'r', label='Target')
plt.xlim(0,x_size)
plt.ylim(-1,1)
plt.legend()
plt.subplot(3, 1, 3)
plt.plot(t_small, y_val[plot_i, -y_size:], 'r', label='Target')
y_val_hat = y_val_hat_cuda.data.cpu().numpy()
plt.plot(t_small, y_val_hat[plot_i, -y_size:], c=(0,0.5,0,0.85), label='Predicted')
plt.ylim(-1,1)
plt.xlim(0,x_size)
plt.legend()
filename = file_prefix + '_' + str(plot_i) + '.png'
savefig(filename)
return
示例10: plot_feat_hist
# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import subplot [as 别名]
def plot_feat_hist(data_name_list, filename=None):
pylab.clf()
num_rows = 1 + (len(data_name_list) - 1) / 2
num_cols = 1 if len(data_name_list) == 1 else 2
pylab.figure(figsize=(5 * num_cols, 4 * num_rows))
for i in range(num_rows):
for j in range(num_cols):
pylab.subplot(num_rows, num_cols, 1 + i * num_cols + j)
x, name = data_name_list[i * num_cols + j]
pylab.title(name)
pylab.xlabel('Value')
pylab.ylabel('Density')
# the histogram of the data
max_val = np.max(x)
if max_val <= 1.0:
bins = 50
elif max_val > 50:
bins = 50
else:
bins = max_val
n, bins, patches = pylab.hist(
x, bins=bins, normed=1, facecolor='green', alpha=0.75)
pylab.grid(True)
if not filename:
filename = "feat_hist_%s.png" % name
pylab.savefig(os.path.join(CHART_DIR, filename), bbox_inches="tight")
开发者ID:PacktPublishing,项目名称:Building-Machine-Learning-Systems-With-Python-Second-Edition,代码行数:32,代码来源:utils.py
示例11: plot_feat_hist
# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import subplot [as 别名]
def plot_feat_hist(data_name_list, filename=None):
if len(data_name_list) > 1:
assert filename is not None
pylab.figure(num=None, figsize=(8, 6))
num_rows = int(1 + (len(data_name_list) - 1) / 2)
num_cols = int(1 if len(data_name_list) == 1 else 2)
pylab.figure(figsize=(5 * num_cols, 4 * num_rows))
for i in range(num_rows):
for j in range(num_cols):
pylab.subplot(num_rows, num_cols, 1 + i * num_cols + j)
x, name = data_name_list[i * num_cols + j]
pylab.title(name)
pylab.xlabel('Value')
pylab.ylabel('Fraction')
# the histogram of the data
max_val = np.max(x)
if max_val <= 1.0:
bins = 50
elif max_val > 50:
bins = 50
else:
bins = max_val
n, bins, patches = pylab.hist(
x, bins=bins, normed=1, alpha=0.75)
pylab.grid(True)
if not filename:
filename = "feat_hist_%s.png" % name.replace(" ", "_")
pylab.savefig(os.path.join(CHART_DIR, filename), bbox_inches="tight")
开发者ID:PacktPublishing,项目名称:Building-Machine-Learning-Systems-With-Python-Second-Edition,代码行数:35,代码来源:utils.py
示例12: plot1D_mat
# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import subplot [as 别名]
def plot1D_mat(a, b, M, title=''):
""" Plot matrix M with the source and target 1D distribution
Creates a subplot with the source distribution a on the left and
target distribution b on the tot. The matrix M is shown in between.
Parameters
----------
a : ndarray, shape (na,)
Source distribution
b : ndarray, shape (nb,)
Target distribution
M : ndarray, shape (na, nb)
Matrix to plot
"""
na, nb = M.shape
gs = gridspec.GridSpec(3, 3)
xa = np.arange(na)
xb = np.arange(nb)
ax1 = pl.subplot(gs[0, 1:])
pl.plot(xb, b, 'r', label='Target distribution')
pl.yticks(())
pl.title(title)
ax2 = pl.subplot(gs[1:, 0])
pl.plot(a, xa, 'b', label='Source distribution')
pl.gca().invert_xaxis()
pl.gca().invert_yaxis()
pl.xticks(())
pl.subplot(gs[1:, 1:], sharex=ax1, sharey=ax2)
pl.imshow(M, interpolation='nearest')
pl.axis('off')
pl.xlim((0, nb))
pl.tight_layout()
pl.subplots_adjust(wspace=0., hspace=0.2)
示例13: __init__
# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import subplot [as 别名]
def __init__(self, fig, gs, num_plots, rows=None, cols=None):
if cols is None:
cols = int(np.floor(np.sqrt(num_plots)))
if rows is None:
rows = int(np.ceil(float(num_plots)/cols))
assert num_plots <= rows*cols, 'Too many plots to put into gridspec.'
self._fig = fig
self._gs = gridspec.GridSpecFromSubplotSpec(8, 1, subplot_spec=gs)
self._gs_legend = self._gs[0:1, 0]
self._gs_plot = self._gs[1:8, 0]
self._ax_legend = plt.subplot(self._gs_legend)
self._ax_legend.get_xaxis().set_visible(False)
self._ax_legend.get_yaxis().set_visible(False)
self._gs_plots = gridspec.GridSpecFromSubplotSpec(rows, cols, subplot_spec=self._gs_plot)
self._axarr = [plt.subplot(self._gs_plots[i], projection='3d') for i in range(num_plots)]
self._lims = [None for i in range(num_plots)]
self._plots = [[] for i in range(num_plots)]
for ax in self._axarr:
ax.tick_params(pad=0)
ax.locator_params(nbins=5)
for item in (ax.get_xticklabels() + ax.get_yticklabels() + ax.get_zticklabels()):
item.set_fontsize(10)
self._fig.canvas.draw()
self._fig.canvas.flush_events() # Fixes bug with Qt4Agg backend
示例14: __init__
# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import subplot [as 别名]
def __init__(self, fig, gs, time_window=500, labels=None, alphas=None):
self._fig = fig
self._gs = gridspec.GridSpecFromSubplotSpec(1, 1, subplot_spec=gs)
self._ax = plt.subplot(self._gs[0])
self._time_window = time_window
self._labels = labels
self._alphas = alphas
self._init = False
if self._labels:
self.init(len(self._labels))
self._fig.canvas.draw()
self._fig.canvas.flush_events() # Fixes bug with Qt4Agg backend
示例15: subplot
# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import subplot [as 别名]
def subplot(data, name, ylabel):
fig = plt.figure(figsize=(20, 6))
ax = plt.subplot(111)
rep_labels = [str(j) for j in reps]
x_pos = [i for i, _ in enumerate(rep_labels)]
X = np.arange(len(data))
ax_plot = ax.bar(x_pos, data, color=color_map(data_normalizer(data)), width=0.45)
plt.xticks(x_pos, rep_labels)
plt.xlabel("Repetitions")
plt.ylabel(ylabel)
autolabel(ax, ax_plot)
plt.savefig(name + ".png")