Python matplotlib.pyplot.draw() Examples
The following are 30
code examples of matplotlib.pyplot.draw().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
matplotlib.pyplot
, or try the search function
.
Example #1
Source File: gen_geometry.py From phidl with MIT License | 6 votes |
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
Example #2
Source File: cam_demo.py From gluon-cv with Apache License 2.0 | 6 votes |
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
Example #3
Source File: vdp_explore.py From compneuro with BSD 3-Clause "New" or "Revised" License | 6 votes |
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'])])
Example #4
Source File: toy_dataset.py From firefly-monte-carlo with MIT License | 6 votes |
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)
Example #5
Source File: vis_utils.py From nucleus7 with Mozilla Public License 2.0 | 6 votes |
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!")
Example #6
Source File: diffdrive_2d_plot.py From SCvx with MIT License | 6 votes |
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()
Example #7
Source File: rocket_landing_2d_plot.py From SCvx with MIT License | 6 votes |
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()
Example #8
Source File: rocket_landing_3d_plot.py From SCvx with MIT License | 6 votes |
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()
Example #9
Source File: visual_callbacks.py From squeezenet-keras with MIT License | 6 votes |
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()
Example #10
Source File: mpplot.py From magpy with BSD 3-Clause "New" or "Revised" License | 6 votes |
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()
Example #11
Source File: toy2d_intractable.py From zhusuan with MIT License | 6 votes |
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)
Example #12
Source File: interactive_labeler.py From libact with BSD 2-Clause "Simplified" License | 6 votes |
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)
Example #13
Source File: pca.py From classification-of-encrypted-traffic with MIT License | 6 votes |
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()
Example #14
Source File: multigoal_env.py From pytorchrl with MIT License | 6 votes |
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()
Example #15
Source File: vis_utils.py From nucleus7 with Mozilla Public License 2.0 | 5 votes |
def draw_dna_helix_on_subplot(dna_helix_graph, subplot, radius: int = 10, verbosity: int = 0): """ Draw the dna helix on given subplot according to verbosity Parameters ---------- dna_helix_graph directed graph with nucleotides as nodes subplot axes subplot to draw on radius radius of nucleotide to draw verbosity verbosity of the visualization; if verbosity == 0, then only the connections between nucleotide are drawn, otherwise connections between nucleotide keys are drawn """ nucleotide_positions = _get_nucleotide_positions( dna_helix_graph, radius) nucleotide_plots = {} for each_nucleotide, each_nucleotide_center in ( nucleotide_positions.items()): nucleotide_plot = draw_nucleotide( each_nucleotide, each_nucleotide_center, subplot, radius=radius) nucleotide_plots[each_nucleotide] = nucleotide_plot draw_dna_connections(dna_helix_graph, nucleotide_plots, subplot=subplot, verbosity=verbosity) subplot.add_callback(lambda subplot_: subplot_.set_aspect('equal')) subplot.autoscale_view() subplot.axis('off') _draw_legend(subplot) _add_update_events(subplot, dna_helix_graph, nucleotide_plots) subplot.pchanged() subplot.figure.canvas.draw() subplot.figure.canvas.flush_events()
Example #16
Source File: Watertools.py From procedural_city_generation with Mozilla Public License 2.0 | 5 votes |
def flood(self, h, pos): """ pos is a pair of indices on heightmap (position where it gets flooded) h is the corresponding height """ stencil=np.array([ [-1, 0], [1, 0], [0, 1], [0, -1] ]) front=[pos] self.flooded_tmp=np.zeros(self.heightmap.shape) while len(front)>0: new_front=[] for x in front: if self.old[x[0]][x[1]]<h: self.flooded_tmp[x[0]][x[1]]=1 new_front.extend( [new for new in x+stencil if not self.flooded_tmp[new[0]][new[1]] == 1 and not np.any(x<=0) and not x[0]>=self.flooded_tmp.shape[0]-2 and not x[1]>=self.flooded_tmp.shape[1]-2] ) plt.imshow(self.flooded_tmp) plt.draw() plt.pause(0.01) front=new_front print(len(front)) self.new=self.old self.new[np.argwhere(self.flooded_tmp)]=h self.flooded[np.argwhere(self.flooded_tmp)]=1 return self.flooded_tmp
Example #17
Source File: user_interface.py From visual_foresight with MIT License | 5 votes |
def onclick(self, event): print(('button=%d, x=%d, y=%d, xdata=%f, ydata=%f' % (event.button, event.x, event.y, event.xdata, event.ydata))) import matplotlib.pyplot as plt self.ax.set_xlim(0, self.im_shape[1]) self.ax.set_ylim(self.im_shape[0], 0) print('iclick', self.i_click) i_task = self.i_click//self.clicks_per_desig print('i_task', i_task) if self.i_click == self.i_click_max: print('saving desig-goal picture') with open(self.basedir +'/{}_pix.pkl'.format(self.suf), 'wb') as f: dict= {'desig_pix': self.desig, 'goal_pix': self.goal} pickle.dump(dict, f) plt.savefig(self.basedir + '/img_' + self.suf) print('closing') plt.close() return rc_coord = np.array([event.ydata, event.xdata]) if self.i_click % self.clicks_per_desig == 0: self.desig[i_task, :] = rc_coord color = "r" else: self.goal[i_task, :] = rc_coord color = "g" marker = self.marker_list[i_task] self.ax.scatter(rc_coord[1], rc_coord[0], s=100, marker=marker, facecolors=color) plt.draw() self.i_click += 1
Example #18
Source File: demo.py From tf_ctpn with MIT License | 5 votes |
def vis_detections(im, class_name, dets, thresh=0.5, text=False): """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, :8] score = dets[i, -1] ax.add_line( plt.Line2D([bbox[0], bbox[2], bbox[6], bbox[4], bbox[0]], [bbox[1], bbox[3], bbox[7], bbox[5], bbox[1]], color='red', linewidth=3) ) if text: 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() plt.show()
Example #19
Source File: pointmass.py From cs294-112_hws with MIT License | 5 votes |
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()
Example #20
Source File: 03_live_emg.py From myo-python with MIT License | 5 votes |
def update_plot(self): emg_data = self.listener.get_emg_data() emg_data = np.array([x[1] for x in emg_data]).T for g, data in zip(self.graphs, emg_data): if len(data) < self.n: # Fill the left side with zeroes. data = np.concatenate([np.zeros(self.n - len(data)), data]) g.set_ydata(data) plt.draw()
Example #21
Source File: demo.py From SSH-TensorFlow with MIT License | 5 votes |
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='green', linewidth=2) ) # 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()
Example #22
Source File: grapher.py From crappy with GNU General Public License v2.0 | 5 votes |
def loop(self): # We need to recv data from all the links, but keep # ALL of the data, even with the same label (so not get_all_last) data = [l.recv_chunk() if l.poll() else {} for l in self.inputs] for i, (lx, ly) in enumerate(self.labels): x = 0 # So that if we don't find it, we do nothing for d in data: if lx in d and ly in d: # Find the first input with both labels dx = d[lx][self.factor[i]-self.counter[i]-1::self.factor[i]] dy = d[ly][self.factor[i]-self.counter[i]-1::self.factor[i]] self.counter[i] = (self.counter[i]+len(d[lx]))%self.factor[i] x = np.hstack((self.lines[i].get_xdata(), dx)) y = np.hstack((self.lines[i].get_ydata(), dy)) break if isinstance(x,int): break if self.length and len(x) >= self.length: # Remove the begining if the graph is dynamic x = x[-self.length:] y = y[-self.length:] elif len(x) > self.maxpt: # Reduce the number of points if we have to many to display print("[Grapher] Too many points on the graph {} ({}>{})".format( i,len(x),self.maxpt)) x,y = x[::2], y[::2] self.factor[i] *= 2 print("[Grapher] Resampling factor is now {}".format(self.factor[i])) self.lines[i].set_xdata(x) self.lines[i].set_ydata(y) self.ax.relim() # Update the window self.ax.autoscale_view(True, True, True) self.f.canvas.draw() # Update the graph self.f.canvas.flush_events()
Example #23
Source File: grapher.py From crappy with GNU General Public License v2.0 | 5 votes |
def prepare(self): if self.backend: plt.switch_backend(self.backend) self.f = plt.figure(figsize=self.window_size) self.ax = self.f.add_subplot(111) self.lines = [] for _ in self.labels: if self.interp: self.lines.append(self.ax.plot([], [])[0]) else: self.lines.append(self.ax.step([], [])[0]) # Keep only 1/factor points on each line self.factor = [1 for i in self.labels] # Count to drop exactly 1/factor points, no more and no less self.counter = [0 for i in self.labels] legend = [y for x, y in self.labels] plt.legend(legend, bbox_to_anchor=(-0.03, 1.02, 1.06, .102), loc=3, ncol=len(legend), mode="expand", borderaxespad=1) plt.xlabel(self.labels[0][0]) plt.ylabel(self.labels[0][1]) plt.grid() self.axclear = plt.axes([.8,.02,.15,.05]) self.bclear = Button(self.axclear,'Clear') self.bclear.on_clicked(self.clear) if self.window_pos: mng = plt.get_current_fig_manager() mng.window.wm_geometry("+%s+%s" % self.window_pos) plt.draw() plt.pause(.001)
Example #24
Source File: rollout_util.py From leap with MIT License | 5 votes |
def debug(env, obs, agent_info): try: import matplotlib.pyplot as plt except ImportError as e: print("could not import matplotlib") global ax1 global ax2 if ax1 is None: _, (ax1, ax2) = plt.subplots(1, 2) subgoal_seq = agent_info['subgoal_seq'] planned_action_seq = agent_info['planned_action_seq'] real_obs_seq = env.true_states( obs, planned_action_seq ) ax1.clear() env.plot_trajectory( ax1, np.array(subgoal_seq), np.array(planned_action_seq), goal=env._target_position, ) ax1.set_title("imagined") ax2.clear() env.plot_trajectory( ax2, np.array(real_obs_seq), np.array(planned_action_seq), goal=env._target_position, ) ax2.set_title("real") plt.draw() plt.pause(0.001)
Example #25
Source File: Train.py From YouTubeCommenter with MIT License | 5 votes |
def plotScores(scores, test_scores, fname, on_top=True): plt.clf() ax = plt.gca() ax.yaxis.tick_right() ax.yaxis.set_ticks_position('both') ax.yaxis.grid(True) plt.plot(scores) plt.plot(test_scores) plt.xlabel('Epoch') plt.tight_layout() loc = ('upper right' if on_top else 'lower right') plt.draw() plt.savefig(fname) #Train model
Example #26
Source File: roipoly.py From roipoly.py with Apache License 2.0 | 5 votes |
def __init__(self, fig=None, ax=None, roi_names=None, color_cycle=('b', 'g', 'r', 'c', 'm', 'y', 'k') ): """ Parameters ---------- fig: matplotlib figure Figure on which to draw the ROIs ax: matplotlib axes Axes on which to draw the ROIs roi_names: list of str Optional names for the ROIs to draw. The ROIs can later be retrieved by using these names as keys for the `self.rois` dictionary. If None, consecutive numbers are used as ROI names color_cycle: list of str List of matplotlib colors for the ROIs """ if fig is None: fig = plt.gcf() if ax is None: ax = fig.gca() self.color_cycle = color_cycle self.roi_names = roi_names self.fig = fig self.ax = ax self.rois = {} self.make_buttons()
Example #27
Source File: roipoly.py From roipoly.py with Apache License 2.0 | 5 votes |
def __motion_notify_callback(self, event): if event.inaxes == self.ax: x, y = event.xdata, event.ydata if ((event.button is None or event.button == 1) and self.line is not None): # Move line around x_data = [self.previous_point[0], x] y_data = [self.previous_point[1], y] logger.debug("draw line x: {} y: {}".format(x_data, y_data)) self.line.set_data(x_data, y_data) self.fig.canvas.draw()
Example #28
Source File: roipoly.py From roipoly.py with Apache License 2.0 | 5 votes |
def display_roi(self, **linekwargs): line = plt.Line2D(self.x + [self.x[0]], self.y + [self.y[0]], color=self.color, **linekwargs) ax = plt.gca() ax.add_line(line) plt.draw()
Example #29
Source File: phaseplane.py From compneuro with BSD 3-Clause "New" or "Revised" License | 5 votes |
def teardown(self): pp.figure(self.curr_fig) if self.x_dom is not None: pp.xlim( self.x_dom ) if self.y_dom is not None: pp.ylim( self.y_dom ) pp.draw()
Example #30
Source File: show_labels.py From 3d-vehicle-tracking with BSD 3-Clause "New" or "Revised" License | 5 votes |
def show(self): # Read and draw image dpi = 80 w = self.image_width / dpi # 16 h = self.image_height / dpi # 9 self.fig = plt.figure(figsize=(w, h), dpi=dpi) self.ax = self.fig.add_axes([0.0, 0.0, 1.0, 1.0], frameon=False) # if len(self.image_paths) > 1: plt.connect('key_release_event', self.next_image) self.show_image() plt.show()