Python matplotlib.pyplot.draw() Examples
The following are 30 code examples for showing how to use matplotlib.pyplot.draw(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.
You may also want to check out all available functions/classes of the module
matplotlib.pyplot
, or try the search function
.
Example 1
Project: magpy Author: geomagpy File: mpplot.py License: 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 2
Project: zhusuan Author: thu-ml File: toy2d_intractable.py License: 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 3
Project: libact Author: ntucllab File: interactive_labeler.py License: 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 4
Project: classification-of-encrypted-traffic Author: SalikLP File: pca.py License: 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 5
Project: phidl Author: amccaugh File: gen_geometry.py License: 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 6
Project: pytorchrl Author: nosyndicate File: multigoal_env.py License: 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 7
Project: squeezenet-keras Author: chasingbob File: visual_callbacks.py License: 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 8
Project: firefly-monte-carlo Author: HIPS File: toy_dataset.py License: 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 9
Project: SCvx Author: EmbersArc File: rocket_landing_3d_plot.py License: 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 10
Project: SCvx Author: EmbersArc File: rocket_landing_2d_plot.py License: 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 11
Project: SCvx Author: EmbersArc File: diffdrive_2d_plot.py License: 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 12
Project: nucleus7 Author: audi File: vis_utils.py License: 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 13
Project: gluon-cv Author: dmlc File: cam_demo.py License: 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 14
Project: compneuro Author: robclewley File: vdp_explore.py License: 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 15
Project: Collaborative-Learning-for-Weakly-Supervised-Object-Detection Author: Sunarker File: demo.py License: 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='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()
Example 16
Project: cs294-112_hws Author: xuwd11 File: pointmass.py License: 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 17
Project: RingNet Author: soubhiksanyal File: demo.py License: MIT License | 5 votes |
def visualize(img, proc_param, verts, cam, img_name='test_image'): """ Renders the result in original image coordinate frame. """ cam_for_render, vert_shifted = vis_util.get_original( proc_param, verts, cam, img_size=img.shape[:2]) # Render results rend_img_overlay = renderer( vert_shifted*1.0, cam=cam_for_render, img=img, do_alpha=True) rend_img = renderer( vert_shifted*1.0, cam=cam_for_render, img_size=img.shape[:2]) rend_img_vp1 = renderer.rotated( vert_shifted, 30, cam=cam_for_render, img_size=img.shape[:2]) import matplotlib.pyplot as plt fig = plt.figure(1) plt.clf() plt.subplot(221) plt.imshow(img) plt.title('input') plt.axis('off') plt.subplot(222) plt.imshow(rend_img_overlay) plt.title('3D Mesh overlay') plt.axis('off') plt.subplot(223) plt.imshow(rend_img) plt.title('3D mesh') plt.axis('off') plt.subplot(224) plt.imshow(rend_img_vp1) plt.title('diff vp') plt.axis('off') plt.draw() plt.show(block=False) fig.savefig(img_name + '.png') # import ipdb # ipdb.set_trace()
Example 18
Project: simnibs Author: simnibs File: nifti_viewer.py License: GNU General Public License v3.0 | 5 votes |
def add_overlay(self, vol, cmap='gray', clim=None, alpha=1., draw=True): ''' volume : array-like The data that will be overlaid. Must have the same dimensions as the original plot cmap: matplotlib colormap, optional Colormap to use for ploting. Default: 'gray' clim: [min, max] or None Limits to use for plotting. Default: 1 and 99th percentiles alpha: float transparency value ''' if len(self._volumes) > 0 and vol.shape != self._volumes[0].shape: raise ValueError('Cannot add overlay, different shape') # add volume self._volumes.append(vol) if clim is None: clim = np.percentile(vol, (1., 99.)) # create new images ims = [] for ii, xax, yax in zip([0, 1, 2], [1, 0, 0], [2, 2, 1]): d = np.zeros((self._sizes[yax], self._sizes[xax])) im = self._axes[ii].imshow( d, aspect=1, cmap=cmap, clim=clim, alpha=alpha, interpolation='nearest', origin='lower' ) ims.append(im) self._ims.append(ims) if draw: self.set_position()
Example 19
Project: simnibs Author: simnibs File: nifti_viewer.py License: GNU General Public License v3.0 | 5 votes |
def draw(self): """Redraw the current image""" for fig in self._figs: fig.canvas.draw()
Example 20
Project: simnibs Author: simnibs File: nifti_viewer.py License: GNU General Public License v3.0 | 5 votes |
def _draw(self): """Update all four (or three) plots""" if self._closed: # make sure we don't draw when we shouldn't return for ii in range(3): ax = self._axes[ii] for im in self._ims: ax.draw_artist(im[ii]) if self._cross: for line in self._crosshairs[ii].values(): ax.draw_artist(line) ax.figure.canvas.blit(ax.bbox)
Example 21
Project: dcc Author: amimo File: main.py License: Apache License 2.0 | 5 votes |
def plot(cg): """ Plot the call graph using matplotlib For larger graphs, this should not be used, as it is very slow and probably you can not see anything on it. :param cg: A networkx call graph to plot """ from androguard.core.analysis.analysis import ExternalMethod import matplotlib.pyplot as plt import networkx as nx pos = nx.spring_layout(cg) internal = [] external = [] for n in cg.node: if isinstance(n, ExternalMethod): external.append(n) else: internal.append(n) nx.draw_networkx_nodes(cg, pos=pos, node_color='r', nodelist=internal) nx.draw_networkx_nodes(cg, pos=pos, node_color='b', nodelist=external) nx.draw_networkx_edges(cg, pos, arrow=True) nx.draw_networkx_labels(cg, pos=pos, labels={x: "{} {}".format(x.get_class_name(), x.get_name()) for x in cg.edge}) plt.draw() plt.show()
Example 22
Project: mnist Author: idea4good File: demo1.py License: Apache License 2.0 | 5 votes |
def UpdateImage(x, y): if(type(x) == None.__class__ or type(x) == None.__class__): return x = int(round(x)) y = int(round(y)) image_y = -(y + 1) if (image_y - 2) < 0 or image_y >= image_height or (x + 2) >= image_width: return axes.add_patch(patches.Rectangle((x , y), 3, 3)) plt.draw() image[image_y][x] = image[image_y][x + 1] = image[image_y][x + 2] = gray image[image_y - 1][x] = image[image_y - 1][x + 1] = image[image_y - 1][x + 2] = gray image[image_y - 2 ][x] = image[image_y - 2][x + 1] = image[image_y - 2][x + 2] = gray
Example 23
Project: mnist Author: idea4good File: demo1.py License: Apache License 2.0 | 5 votes |
def update_figure(result): if result == -1: axes.set_xlabel("") else: axes.set_xlabel("Predict: {0}".format(result)) plt.draw()
Example 24
Project: mnist Author: idea4good File: demo2.py License: Apache License 2.0 | 5 votes |
def UpdateImage(x, y): if(type(x) == None.__class__ or type(x) == None.__class__): return x = int(round(x)) y = int(round(y)) image_y = -(y + 1) if (image_y - 2) < 0 or image_y >= image_height or (x + 2) >= image_width: return axes.add_patch(patches.Rectangle((x , y), 3, 3)) plt.draw() image[image_y][x] = image[image_y][x + 1] = image[image_y][x + 2] = gray image[image_y - 1][x] = image[image_y - 1][x + 1] = image[image_y - 1][x + 2] = gray image[image_y - 2 ][x] = image[image_y - 2][x + 1] = image[image_y - 2][x + 2] = gray
Example 25
Project: mnist Author: idea4good File: demo2.py License: Apache License 2.0 | 5 votes |
def update_figure(result): if result == -1: axes.set_xlabel("") else: axes.set_xlabel("Predict: {0}".format(result)) plt.draw()
Example 26
Project: VRPTW-ga Author: shayan-ys File: report.py License: MIT License | 5 votes |
def plot_draw(self, x_axis: list, y_axis: list, latest_result): y_axis_parsed = [] for y in y_axis: try: y_axis_parsed.append(y['best']) except: break if y_axis_parsed: y_axis = y_axis_parsed plt.figure(1) # self.subplot.set_xlim([self.plot_x_axis[0], self.plot_x_axis[-1]]) self.subplot.set_ylim([min(y_axis) - 5, max(y_axis) + 5]) plt.suptitle('Best solution so far: ' + re.sub("(.{64})", "\\1\n", str(latest_result), 0, re.DOTALL), fontsize=10) print(latest_result) self.subplot.plot(x_axis, y_axis) plt.figure(2) for route_x, route_y in latest_result.plot_get_route_cords(): plt.plot(route_x, route_y) plt.draw() self.fig.savefig("plot-output.png") self.fig_node_connector.savefig("plot2-output.png") plt.pause(0.000001)
Example 27
Project: TGC-Designer-Tools Author: chadrockey File: offset_ui_tool.py License: Apache License 2.0 | 5 votes |
def drawNewImage(ax, image_dict, label): ax.imshow(image_dict[label], origin='lower') plt.draw()
Example 28
Project: garden.matplotlib Author: kivy-garden File: backend_kivy.py License: MIT License | 5 votes |
def get_graphics(self, gc, polygons, points_line, rgbFace, closed=False): '''Return an instruction group which contains the necessary graphics instructions to draw the respective graphics. ''' instruction_group = InstructionGroup() if isinstance(gc.line['dash_list'], tuple): gc.line['dash_list'] = list(gc.line['dash_list']) if rgbFace is not None: if len(polygons.meshes) != 0: instruction_group.add(Color(*rgbFace)) for vertices, indices in polygons.meshes: instruction_group.add(Mesh( vertices=vertices, indices=indices, mode=str("triangle_fan") )) instruction_group.add(Color(*gc.get_rgb())) if _mpl_ge_1_5 and (not _mpl_ge_2_0) and closed: points_poly_line = points_line[:-2] else: points_poly_line = points_line if gc.line['width'] > 0: instruction_group.add(Line(points=points_poly_line, width=int(gc.line['width'] / 2), dash_length=gc.line['dash_length'], dash_offset=gc.line['dash_offset'], dash_joint=gc.line['join_style'], dash_list=gc.line['dash_list'])) return instruction_group
Example 29
Project: garden.matplotlib Author: kivy-garden File: backend_kivy.py License: MIT License | 5 votes |
def draw(self): '''Draw the figure using the KivyRenderer ''' self.clear_widgets() self.canvas.clear() self._renderer = RendererKivy(self) self.figure.draw(self._renderer)
Example 30
Project: garden.matplotlib Author: kivy-garden File: backend_kivy.py License: MIT License | 5 votes |
def _on_pos_changed(self, *args): self.draw()