本文整理匯總了Python中matplotlib.pyplot.draw方法的典型用法代碼示例。如果您正苦於以下問題:Python pyplot.draw方法的具體用法?Python pyplot.draw怎麽用?Python pyplot.draw使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類matplotlib.pyplot
的用法示例。
在下文中一共展示了pyplot.draw方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: hzfunc
# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import draw [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()
示例2: draw
# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import draw [as 別名]
def draw(vmean, vlogstd):
from scipy import stats
plt.cla()
xlimits = [-2, 2]
ylimits = [-4, 2]
def log_prob(z):
z1, z2 = z[:, 0], z[:, 1]
return stats.norm.logpdf(z2, 0, 1.35) + \
stats.norm.logpdf(z1, 0, np.exp(z2))
plot_isocontours(ax, lambda z: np.exp(log_prob(z)), xlimits, ylimits)
def variational_contour(z):
return stats.multivariate_normal.pdf(
z, vmean, np.diag(np.exp(vlogstd)))
plot_isocontours(ax, variational_contour, xlimits, ylimits)
plt.draw()
plt.pause(1.0 / 30.0)
示例3: label
# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import draw [as 別名]
def label(self, feature):
plt.imshow(feature, cmap=plt.cm.gray_r, interpolation='nearest')
plt.draw()
banner = "Enter the associated label with the image: "
if self.label_name is not None:
banner += str(self.label_name) + ' '
lbl = input(banner)
while (self.label_name is not None) and (lbl not in self.label_name):
print('Invalid label, please re-enter the associated label.')
lbl = input(banner)
return self.label_name.index(lbl)
示例4: plotprojection
# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import draw [as 別名]
def plotprojection(Z, pc, labels, class_labels):
diff_labels = np.unique(labels)
opacity = 0.8
fig, ax = plt.subplots()
color_map = {0: 'orangered', 1: 'royalblue', 2: 'lightgreen', 3: 'darkorchid', 4: 'teal', 5: 'darkslategrey',
6: 'darkgreen', 7: 'darkgrey'}
for label in diff_labels:
idx = labels == label
ax.plot(Z[idx, pc], Z[idx, pc + 1], 'o', alpha=opacity, c=color_map[label], label='{label}'.format(label=class_labels[label]))
# ax.plot(Z[idx_below, pc], Z[idx_below, pc + 1], 'o', alpha=opacity,
# label='{name} below mean'.format(name=attributeNames[att]))
ax.set_ylabel('$v{0}$'.format(pc + 2))
ax.set_xlabel('$v{0}$'.format(pc + 1))
ax.legend()
ax.set_title('Data projected on v{0} and v{1}'.format(pc+1, pc+2))
# fig.savefig('v{0}_v{1}_{att}.png'.format(pc + 1, pc + 2, att=attributeNames[att]), dpi=300)
plt.draw()
示例5: create_image
# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import draw [as 別名]
def create_image(D, filename, filepath = '_static/'):
# if any(D.size == 0):
# D = pg.text('?')
qp(D)
fig = plt.gcf()
# ax = plt.gca()
scale = 0.75
fig.set_size_inches(10*scale, 4*scale, forward=True)
# ax.autoscale()
# plt.draw()
# plt.show(block = False)
filename += '.png'
filepathfull = os.path.join(os.path.curdir, filepath, filename)
print(filepathfull)
fig.savefig(filepathfull, dpi=int(96/scale))
# example-rectangle
示例6: render
# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import draw [as 別名]
def render(self, close=False):
if self.fig is None:
self.fig = plt.figure()
self.ax = self.fig.add_subplot(111)
plt.axis('equal')
if self.fixed_plots is None:
self.fixed_plots = self.plot_position_cost(self.ax)
[o.remove() for o in self.dynamic_plots]
x, y = self.observation
point = self.ax.plot(x, y, 'b*')
self.dynamic_plots = point
if close:
self.fixed_plots = None
plt.pause(0.001)
plt.draw()
示例7: update
# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import draw [as 別名]
def update(self, conf_mat, classes, normalize=False):
"""This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
plt.imshow(conf_mat, interpolation='nearest', cmap=self.cmap)
plt.title(self.title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
if normalize:
conf_mat = conf_mat.astype('float') / conf_mat.sum(axis=1)[:, np.newaxis]
thresh = conf_mat.max() / 2.
for i, j in itertools.product(range(conf_mat.shape[0]), range(conf_mat.shape[1])):
plt.text(j, i, conf_mat[i, j],
horizontalalignment="center",
color="white" if conf_mat[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
plt.draw()
示例8: main
# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import draw [as 別名]
def main():
# Generate synthetic data
x = 2 * npr.rand(N,D) - 1 # data features, an (N,D) array
x[:, 0] = 1
th_true = 10.0 * np.array([0, 1, 1])
y = np.dot(x, th_true[:, None])[:, 0]
t = npr.rand(N) > (1 / ( 1 + np.exp(y))) # data targets, an (N) array of 0s and 1s
# Obtain joint distributions over z and th
model = ff.LogisticModel(x, t, th0=th0, y0=y0)
# Set up step functions
th = np.random.randn(D) * th0
z = ff.BrightnessVars(N)
th_stepper = ff.ThetaStepMH(model.log_p_joint, stepsize)
z__stepper = ff.zStepMH(model.log_pseudo_lik, q)
plt.ion()
ax = plt.figure(figsize=(8, 6)).add_subplot(111)
while True:
th = th_stepper.step(th, z) # Markov transition step for theta
z = z__stepper.step(th ,z) # Markov transition step for z
update_fig(ax, x, y, z, th, t)
plt.draw()
plt.pause(0.05)
示例9: key_press_event
# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import draw [as 別名]
def key_press_event(event):
global figures_i
fig = event.canvas.figure
if event.key == 'q' or event.key == 'escape':
plt.close(event.canvas.figure)
return
if event.key == 'right':
figures_i = (figures_i + 1) % figures_N
elif event.key == 'left':
figures_i = (figures_i - 1) % figures_N
fig.clear()
my_plot(fig, figures_i)
plt.draw()
示例10: key_press_event
# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import draw [as 別名]
def key_press_event(event):
global figures_i, figures_N
fig = event.canvas.figure
if event.key == 'q' or event.key == 'escape':
plt.close(event.canvas.figure)
return
if event.key == 'right':
figures_i += 1
figures_i %= figures_N
elif event.key == 'left':
figures_i -= 1
figures_i %= figures_N
fig.clear()
my_plot(fig, figures_i)
plt.draw()
示例11: _create_subgraph_plot
# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import draw [as 別名]
def _create_subgraph_plot(event, dna_helix_graph: nx.DiGraph):
mouseevent = event.mouseevent
if not mouseevent.dblclick or mouseevent.button != 1:
return
logger = logging.getLogger(__name__)
nucleotide_name = event.artist.get_label().split(":")[-1]
nucleotide = _get_nucleotide_by_name(nucleotide_name, dna_helix_graph)
logger.info("Create subgraph plot for %s", nucleotide_name)
figure, subplot = _create_figure_with_subplot()
figure.suptitle("Subgraph of nucleotide {}".format(nucleotide_name))
nucleotide_with_neighbors_subgraph = _get_nucleotide_subgraph(
dna_helix_graph, nucleotide)
draw_dna_helix_on_subplot(
nucleotide_with_neighbors_subgraph, subplot, verbosity=1)
_draw_click_instructions(subplot, doubleclick=False)
plt.draw()
logger.info("Done!")
示例12: keypoint_detection
# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import draw [as 別名]
def keypoint_detection(img, detector, pose_net, ctx=mx.cpu(), axes=None):
x, img = gcv.data.transforms.presets.yolo.transform_test(img, short=512, max_size=350)
x = x.as_in_context(ctx)
class_IDs, scores, bounding_boxs = detector(x)
plt.cla()
pose_input, upscale_bbox = detector_to_alpha_pose(img, class_IDs, scores, bounding_boxs,
output_shape=(128, 96), ctx=ctx)
if len(upscale_bbox) > 0:
predicted_heatmap = pose_net(pose_input)
pred_coords, confidence = heatmap_to_coord_alpha_pose(predicted_heatmap, upscale_bbox)
axes = plot_keypoints(img, pred_coords, confidence, class_IDs, bounding_boxs, scores,
box_thresh=0.5, keypoint_thresh=0.2, ax=axes)
plt.draw()
plt.pause(0.001)
else:
axes = plot_image(frame, ax=axes)
plt.draw()
plt.pause(0.001)
return axes
示例13: ampl
# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import draw [as 別名]
def ampl(a):
global i
vdp.set(pars={'a': a},
ics={'x': 0, 'y': 0},
tdata=[0,20])
# let solution settle
transient = vdp.compute('trans')
vdp.set(ics=transient(20),
tdata=[0,6])
traj = vdp.compute('ampl')
pts = traj.sample()
if mod(i, 10) == 0 or 1-abs(a) < 0.02:
plt.figure(3)
plt.plot(pts['x'], pts['y'], 'k-')
plt.draw()
i += 1
return np.linalg.norm([max(pts['x']) - min(pts['x']), max(pts['y']) - min(pts['y'])])
示例14: vis_detections
# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import draw [as 別名]
def vis_detections(im, class_name, dets, thresh=0.5):
"""Draw detected bounding boxes."""
inds = np.where(dets[:, -1] >= thresh)[0]
if len(inds) == 0:
return
im = im[:, :, (2, 1, 0)]
fig, ax = plt.subplots(figsize=(12, 12))
ax.imshow(im, aspect='equal')
for i in inds:
bbox = dets[i, :4]
score = dets[i, -1]
ax.add_patch(
plt.Rectangle((bbox[0], bbox[1]),
bbox[2] - bbox[0],
bbox[3] - bbox[1], fill=False,
edgecolor='red', linewidth=3.5)
)
ax.text(bbox[0], bbox[1] - 2,
'{:s} {:.3f}'.format(class_name, score),
bbox=dict(facecolor='blue', alpha=0.5),
fontsize=14, color='white')
ax.set_title(('{} detections with '
'p({} | box) >= {:.1f}').format(class_name, class_name,
thresh),
fontsize=14)
plt.axis('off')
plt.tight_layout()
plt.draw()
開發者ID:Sunarker,項目名稱:Collaborative-Learning-for-Weakly-Supervised-Object-Detection,代碼行數:33,代碼來源:demo.py
示例15: render
# 需要導入模塊: from matplotlib import pyplot [as 別名]
# 或者: from matplotlib.pyplot import draw [as 別名]
def render(self):
# create a grid
states = [self.state/self.scale]
indices = np.array([int(self.preprocess(s)) for s in states])
a = np.zeros(self.grid_size)
for i in indices:
a[i] += 1
max_freq = np.max(a)
a/=float(max_freq) # normalize
a = np.reshape(a, (self.scale, self.scale))
ax = sns.heatmap(a)
plt.draw()
plt.pause(0.001)
plt.clf()