我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用matplotlib.pyplot.hold()。
def plot_axes_scaling(self, iabscissa=1): from matplotlib import pyplot if not hasattr(self, 'D'): self.load() dat = self if np.max(dat.D[:, 5:]) == np.min(dat.D[:, 5:]): pyplot.text(0, dat.D[-1, 5], 'all axes scaling values equal to %s' % str(dat.D[-1, 5]), verticalalignment='center') return self # nothing interesting to plot self._enter_plotting() pyplot.semilogy(dat.D[:, iabscissa], dat.D[:, 5:], '-b') # pyplot.hold(True) pyplot.grid(True) ax = array(pyplot.axis()) # ax[1] = max(minxend, ax[1]) pyplot.axis(ax) pyplot.title('Principle Axes Lengths') # pyplot.xticks(xticklocs) self._xlabel(iabscissa) self._finalize_plotting() return self
def plot_axes_scaling(self, iabscissa=1): if not hasattr(self, 'D'): self.load() dat = self self._enter_plotting() pyplot.semilogy(dat.D[:, iabscissa], dat.D[:, 5:], '-b') pyplot.hold(True) pyplot.grid(True) ax = array(pyplot.axis()) # ax[1] = max(minxend, ax[1]) pyplot.axis(ax) pyplot.title('Principle Axes Lengths') # pyplot.xticks(xticklocs) self._xlabel(iabscissa) self._finalize_plotting() return self
def plotDGM(dgm, color = 'b', sz = 20, label = 'dgm', axcolor = np.array([0.0, 0.0, 0.0]), marker = None): if dgm.size == 0: return # Create Lists # set axis values axMin = np.min(dgm) axMax = np.max(dgm) axRange = axMax-axMin a = max(axMin - axRange/5, 0) b = axMax+axRange/5 # plot line plt.plot([a, b], [a, b], c = axcolor, label = 'none') plt.hold(True) # plot points if marker: H = plt.scatter(dgm[:, 0], dgm[:, 1], sz, color, marker, label=label, edgecolor = 'none') else: H = plt.scatter(dgm[:, 0], dgm[:, 1], sz, color, label=label, edgecolor = 'none') # add labels plt.xlabel('Time of Birth') plt.ylabel('Time of Death') return H
def viz_textbb(fignum,text_im, bb_list,alpha=1.0): """ text_im : image containing text bb_list : list of 2x4xn_i boundinb-box matrices """ plt.close(fignum) plt.figure(fignum) plt.imshow(text_im) plt.hold(True) H,W = text_im.shape[:2] for i in xrange(len(bb_list)): bbs = bb_list[i] ni = bbs.shape[-1] for j in xrange(ni): bb = bbs[:,:,j] bb = np.c_[bb,bb[:,0]] plt.plot(bb[0,:], bb[1,:], 'r', linewidth=2, alpha=alpha) plt.gca().set_xlim([0,W-1]) plt.gca().set_ylim([H-1,0]) plt.show(block=False)
def cvglmnetPlot(cvobject, sign_lambda = 1.0, **options): sloglam = sign_lambda*scipy.log(cvobject['lambdau']) fig = plt.gcf() ax1 = plt.gca() #fig, ax1 = plt.subplots() plt.errorbar(sloglam, cvobject['cvm'], cvobject['cvsd'], \ ecolor = (0.5, 0.5, 0.5), \ **options ) plt.hold(True) plt.plot(sloglam, cvobject['cvm'], linestyle = 'dashed',\ marker = 'o', markerfacecolor = 'r') xlim1 = ax1.get_xlim() ylim1 = ax1.get_ylim() xval = sign_lambda*scipy.log(scipy.array([cvobject['lambda_min'], cvobject['lambda_min']])) plt.plot(xval, ylim1, color = 'b', linestyle = 'dashed', \ linewidth = 1) if cvobject['lambda_min'] != cvobject['lambda_1se']: xval = sign_lambda*scipy.log([cvobject['lambda_1se'], cvobject['lambda_1se']]) plt.plot(xval, ylim1, color = 'b', linestyle = 'dashed', \ linewidth = 1) ax2 = ax1.twiny() ax2.xaxis.tick_top() atdf = ax1.get_xticks() indat = scipy.ones(atdf.shape, dtype = scipy.integer) if sloglam[-1] >= sloglam[1]: for j in range(len(sloglam)-1, -1, -1): indat[atdf <= sloglam[j]] = j else: for j in range(len(sloglam)): indat[atdf <= sloglam[j]] = j prettydf = cvobject['nzero'][indat] ax2.set(XLim=xlim1, XTicks = atdf, XTickLabels = prettydf) ax2.grid() ax1.yaxis.grid() ax2.set_xlabel('Degrees of Freedom') # plt.plot(xlim1, [ylim1[1], ylim1[1]], 'b') # plt.plot([xlim1[1], xlim1[1]], ylim1, 'b') if sign_lambda < 0: ax1.set_xlabel('-log(Lambda)') else: ax1.set_xlabel('log(Lambda)') ax1.set_ylabel(cvobject['name']) #plt.show()
def save_heatmap(heatmap, mask): plt.clf() xmin, xmax, ymin, ymax = 0, heatmap.shape[1], heatmap.shape[0], 0 extent = xmin, xmax, ymin, ymax alpha=1.0 if mask is not None: alpha=0.5 xmin, xmax, ymin, ymax = (0, max(heatmap.shape[1], mask.shape[1]), max(heatmap.shape[0], mask.shape[0]), 0) extent = xmin, xmax, ymin, ymax plt.imshow(mask, extent=extent) plt.hold(True) plt.suptitle("Heatmap of sampled tiles.") plt.imshow(heatmap, cmap='gnuplot', interpolation='nearest', extent=extent, alpha=alpha) return plt
def plotLinePatches(P, name): plotPatches(P) plt.savefig("%sPatches.svg"%name, bbox_inches='tight') plt.clf() sio.savemat("P%s.mat"%name, {"P":P}) plt.subplot(121) PDs = doRipsFiltration(P, 2, coeff = 2) print PDs[2] H1 = plotDGM(PDs[1], color = np.array([1.0, 0.0, 0.2]), label = 'H1', sz = 50, axcolor = np.array([0.8]*3)) plt.hold(True) H2 = plotDGM(PDs[2], color = np.array([0.43, 0.67, 0.27]), marker = 'x', sz = 50, label = 'H2', axcolor = np.array([0.8]*3)) plt.title("$\mathbb{Z}2$ Coefficients") plt.subplot(122) PDs = doRipsFiltration(P, 2, coeff = 3) print PDs[2] H1 = plotDGM(PDs[1], color = np.array([1.0, 0.0, 0.2]), label = 'H1', sz = 50, axcolor = np.array([0.8]*3)) plt.hold(True) H2 = plotDGM(PDs[2], color = np.array([0.43, 0.67, 0.27]), marker = 'x', sz = 50, label = 'H2', axcolor = np.array([0.8]*3)) plt.title("$\mathbb{Z}3$ Coefficients") plt.show()
def draw(self, q, color='b', show=False, base_color='g'): ''' Draw the robot with the provided configuration ''' plotter.hold(True) pts = self.fk(q) for i, p in enumerate(pts): if i == 0: style = base_color+'o' else: style = color+'o' plotter.plot(p[0], p[1], style) if i > 0: plotter.plot([prev_p[0], p[0]], [prev_p[1], p[1]], color) prev_p = p[:] if show: plotter.show()
def plot_points(X, barycentric=True, border=True, **kwargs): '''Plots a set of points in the simplex. Arguments: `X` (ndarray): A 2xN array (if in Cartesian coords) or 3xN array (if in barycentric coords) of points to plot. `barycentric` (bool): Indicates if `X` is in barycentric coords. `border` (bool): If True, the simplex border is drawn. kwargs: Keyword args passed on to `plt.plot`. ''' if barycentric is True: X = X.dot(corners) plt.plot(X[:, 0], X[:, 1], 'k.', ms=1, **kwargs) plt.axis('equal') plt.xlim(0, 1) plt.ylim(0, 0.75**0.5) plt.axis('off') if border is True: plt.hold(1) plt.triplot(triangle, linewidth=1)
def plotSinglePitchTrack(fromTuple, fnFullPath): _matplotlibCheck() plt.hold(True) fig, (ax0) = plt.subplots(nrows=1) # Old data plot1 = ax0.plot(fromTuple, color='red', linewidth=2, ) plt.ylabel('Pitch (Hz)') plt.xlabel('Sample number') plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) # plt.legend([plot1, plot2, plot3], ["From", "To", "Merged line"]) plt.savefig(fnFullPath, dpi=300, bbox_inches='tight') plt.close(fig)
def getBarycentricCoords(A, B, C, X, checkValidity = True): T = np.array( [ [A.x - C.x, B.x - C.x ], [A.y - C.y, B.y - C.y] ] ) y = np.array( [ [X.x - C.x], [X.y - C.y] ] ) lambdas = linalg.solve(T, y) lambdas = lambdas.flatten() lambdas = np.append(lambdas, 1 - (lambdas[0] + lambdas[1])) if checkValidity: if (lambdas[0] < 0 or lambdas[1] < 0 or lambdas[2] < 0): print "ERROR: Not a convex combination; lambda = %s"%lambdas print "pointInsideConvexPolygon2D = %s"%pointInsideConvexPolygon2D([A, B, C], X, 0) plt.plot([A.x, B.x, C.x, A.x], [A.y, B.y, C.y, A.y], 'r') plt.hold(True) plt.plot([X.x], [X.y], 'b.') plt.show() assert (lambdas[0] >= 0 and lambdas[1] >= 0 and lambdas[2] >= 0) else: lambdas[0] = max(lambdas[0], 0) lambdas[1] = max(lambdas[1], 0) lambdas[2] = max(lambdas[2], 0) return lambdas
def dirClassificationSentiment(dirName, modelName, modelType): types = ('*.jpg', '*.png',) filesList = [] for files in types: filesList.extend(glob.glob(os.path.join(dirName, files))) filesList = sorted(filesList) print filesList Features = [] plt.close('all'); ax = plt.gca() plt.hold(True) for fi in filesList: P, classNames = fileClassification(fi, modelName, modelType) im = cv2.imread(fi, cv2.CV_LOAD_IMAGE_COLOR) Width = 0.1; Height = 0.1; startX = P[classNames.index("positive")]; startY = 0; myaximage = ax.imshow(cv2.cvtColor(im, cv2.cv.CV_RGB2BGR), extent=(startX-Width/2.0, startX+Width/2.0, startY-Height/2.0, startY+Height/2.0), alpha=1.0, zorder=-1) plt.axis((0,1,-0.1,0.1)) plt.show(block = False); plt.draw() plt.show(block = True);
def save_test1_fig(name): with open("test1/{}.pkl".format(name), "rb") as f: results = pickle.load(f) fps, acc, var = [], [], [] for r in results: fps.append(r["fps"]) acc.append(r["accuracy"]) var.append(r["config"][name]) plt.hold(True) plt.plot(var, fps, color="blue") plt.plot(var, acc, color="red") plt.legend(handles=[ ptc.Patch(color='blue', label='FPS'), ptc.Patch(color='red', label='Accuracy') ]) plt.xlabel(name) plt.savefig("test1/{}.png".format(name)) plt.hold(False) plt.close()
def plot_correlation(flname, title, x_label, y_label, dataset): """ Scatter plot with line of best fit dataset - tuple of (x_values, y_values) """ plt.clf() plt.hold(True) plt.scatter(dataset[0], dataset[1], alpha=0.7, color="k") xs = np.array(dataset[0]) ys = np.array(dataset[1]) A = np.vstack([xs, np.ones(len(xs))]).T m, c = np.linalg.lstsq(A, ys)[0] plt.plot(xs, m*xs + c, "c-") plt.xlabel(x_label, fontsize=16) plt.ylabel(y_label, fontsize=16) plt.xlim([0.25, max(dataset[0])]) plt.ylim([10., max(dataset[1])]) plt.title(title, fontsize=18) plt.savefig(flname, DPI=200)
def plot_histogram(flname, title, x_label, datasets): """ Histogram dataset - list tuples of (frequencies, bins, style) """ plt.clf() plt.hold(True) max_bin = 0 for frequencies, bins, style in datasets: xs = [] ys = [] max_bin = max(max_bin, max(bins)) for i, f in enumerate(frequencies): xs.append(bins[i]) xs.append(bins[i+1]) ys.append(f) ys.append(f) plt.plot(xs, ys, style) plt.xlabel(x_label, fontsize=16) plt.ylabel("Occurrences", fontsize=16) plt.xlim([0, max_bin + 1]) plt.title(title, fontsize=18) plt.savefig(flname, DPI=200)
def __init__(self,ASN): self.filename = str(ASN) + 'network graph' self.alias_filename = str(ASN) + 'alias_candidates.txt' self.ISP_Network = networkx.Graph() self.files_read = 0 self.border_points = set() if os.path.isfile(self.filename): load_file = shelve.open(self.filename, 'r') self.files_read = load_file['files_read'] self.ISP_Network = load_file['ISP_Network'] self.border_points = load_file['border_points'] self.ASN = ASN plt.ion() country = raw_input('enter country to focus on map [Israel/Usa/Australia/other]: ') if country == 'Israel' or country == 'israel' or country == 'ISRAEL': self.wmap = Basemap(projection='aeqd', lat_0 = 31.4, lon_0 = 35, width = 200000, height = 450000, resolution = 'i') elif country == 'USA' or country == 'usa': self.wmap = Basemap(projection='aeqd', lat_0 = 40, lon_0 = -98, width = 4500000, height = 2700000, resolution = 'i') elif country == 'Australia' or 'australia' or 'AUSTRALIA': self.wmap = Basemap(projection='aeqd', lat_0 = -23.07, lon_0 = 132.08, width = 4500000, height = 3500000, resolution = 'i') else: self.wmap = Basemap(projection='cyl', resolution = 'c') plt.hold(False)
def draw_ori_on_img(img, ori, mask, fname, coh=None, stride=16): ori = np.squeeze(ori) mask = np.squeeze(np.round(mask)) img = np.squeeze(img) ori = ndimage.zoom(ori, np.array(img.shape)/np.array(ori.shape, dtype=float), order=0) if mask.shape != img.shape: mask = ndimage.zoom(mask, np.array(img.shape)/np.array(mask.shape, dtype=float), order=0) if coh is None: coh = np.ones_like(img) fig = plt.figure() plt.imshow(img,cmap='gray') plt.hold(True) for i in xrange(stride,img.shape[0],stride): for j in xrange(stride,img.shape[1],stride): if mask[i, j] == 0: continue x, y, o, r = j, i, ori[i,j], coh[i,j]*(stride*0.9) plt.plot([x, x+r*np.cos(o)], [y, y+r*np.sin(o)], 'r-') plt.axis([0,img.shape[1],img.shape[0],0]) plt.axis('off') plt.savefig(fname, bbox_inches='tight', pad_inches = 0) plt.close(fig) return
def show(img, show_max=False): '''show response map''' img = img - img.min() img = img / img.max() plt.imshow(img, cmap='gray') shape = img.shape idx = np.argmax(img) hi = idx / shape[1] wi = idx % shape[1] print hi, wi if show_max: plt.hold(True) plt.plot(wi, hi, 'r.', markersize=12) plt.axis('off') plt.axis('image') plt.show()
def displayLogErrors(self, legendList): if self.count != 0: err = numpy.array(self.errorsList) for e in err: e = numpy.array(e) err = numpy.array(err) plt.hold(True) if numpy.ndim(err) == 2: for ii in range(0, len(self.errorsList[-1])): plt.semilogy(range(0, self.count), abs(err[:, ii]), label=legendList[ii]) plt.hold(False) else: plt.semilogy(range(0, self.count), abs(err), label=legendList[0]) plt.grid(True) plt.ylabel("erros []") plt.xlabel("iteration number []") plt.title(self.name) # if self.name == 'All errors': plt.legend() plt.show()
def displayFactors(self, legendList): if self.count != 0: err = numpy.array(self.factorsList) for e in err: e = numpy.array(e) err = numpy.array(err) plt.hold(True) if numpy.ndim(err) == 2: for ii in range(0, len(self.factorsList[-1])): plt.plot(range(0, self.count), abs(err[:, ii]), label=legendList[ii]) plt.hold(False) else: plt.plot(range(0, self.count), abs(err), label=legendList[0]) plt.grid(True) plt.ylabel("factors []") plt.xlabel("iteration number []") plt.title(self.name) # if self.name == 'All errors': plt.legend() plt.show()
def sliparcdiscretization(pointAtToeVec, pointAtCrownVec, nDivs, slipArcSTR,\ want2plot = False ): ## Doing the math xCoordIni = pointAtCrownVec[0] xCoordEnd = pointAtToeVec[0] xCoords = np.linspace(xCoordIni, xCoordEnd, nDivs+1) yCoords = slipArcSTR['center'][1]-np.sqrt(slipArcSTR['radius']**2\ -(xCoords-slipArcSTR['center'][0])**2) arcPointsCoordsArray = np.transpose(np.vstack((xCoords, yCoords))) arcPointsCoordsArray = np.flipud(arcPointsCoordsArray) ## Plotting the arc if want2plot: plt.hold(True) plt.axis('equal') plt.plot(arcPointsCoordsArray[:,0], arcPointsCoordsArray[:,1], 'g-') plt.grid(True) plt.show(False) return arcPointsCoordsArray
def update_image_display(self): plt.hold(False) self.imax.imshow(self.images[self.current_image]) plt.hold(True) if self.detection_run: if self.chessboard_status[self.current_image]: status_string = ' - Chessboard Detected OK' else: status_string = ' - Chessboard Detection FAILED' else: status_string = '' self.current_filename.setText('<html><head/><body><p align="center">{:s} [#{:d}/{:d}]{:s}</p></body></html>'.format(self.filenames[self.current_image],self.current_image+1,len(self.images),status_string)) if self.chessboard_status[self.current_image]: xl = plt.xlim() yl = plt.ylim() self.imax.plot(self.chessboard_points_2D[self.current_image][:,0],self.chessboard_points_2D[self.current_image][:,1],color='lime',marker='o',linestyle='None') plt.xlim(xl) plt.ylim(yl) self.mplwidget.draw()
def fig_memory_usage(): # FAST memory x = [1,3,7,14,30,90,180] y_fast = [0.653,1.44,2.94,4.97,9.05,19.9,35.2] # ConvNetQuake y_convnet = [6.8*1e-5]*7 # Create figure plt.loglog(x,y_fast,"o-") plt.hold('on') plt.loglog(x,y_convnet,"o-") # plot markers plt.loglog(x,[1e-5,1e-5,1e-5,1e-5,1e-5,1e-5,1e-5],'o') plt.ylabel("Memory usage (GB)") plt.xlabel("Continous data duration (days)") plt.xlim(1,180) plt.grid("on") plt.savefig("./figures/memoryusage.eps") plt.close()
def fig_run_time(): # fast run time x_fast = [1,3,7,14,30,90,180] y_fast = [289,1.13*1e3,2.48*1e3,5.41*1e3,1.56*1e4, 6.61*1e4,1.98*1e5] x_auto = [1,3] y_auto = [1.54*1e4, 8.06*1e5] x_convnet = [1,3,7,14,30] y_convnet = [9,27,61,144,291] # create figure plt.loglog(x_auto,y_auto,"o-") plt.hold('on') plt.loglog(x_fast[0:5],y_fast[0:5],"o-") plt.loglog(x_convnet,y_convnet,"o-") # plot x markers plt.loglog(x_convnet,[1e0]*len(x_convnet),'o') # plot y markers y_markers = [1,60,3600,3600*24] plt.plot([1]*4,y_markers,'ko') plt.ylabel("run time (s)") plt.xlabel("continous data duration (days)") plt.xlim(1,35) plt.grid("on") plt.savefig("./figures/runtimes.eps")
def main(): plt.close('all') plt.figure(facecolor='w') plt.hold(True) throw_y, throw_z, vel, alpha = find_feasible_release(catch_x, catch_y, catch_z, pos) block_width = .047 dy = catch_y - throw_y - block_width t = np.linspace(0,dy/(vel*cos(alpha)),100) traj_y = vel*cos(alpha)*t + throw_y; traj_z = -.5*9.8*t**2 + vel*sin(alpha)*t + throw_z plt.plot(traj_y,traj_z,'r',linewidth=2) plt.plot(traj_y[0],traj_z[0],'r.',markersize=15) plt.ylim([-.6, .5]) plt.xlabel('Y position (m)') plt.ylabel('Z position (m)') plt.title('Trajectories for sample release position, velocity, and angle') plt.show(block=False)
def test_on_SUP_model(sup_model_name, x, y): SUP_MODEL = load_model(sup_model_name, custom_objects={"contrastive_loss": contrastive_loss}) model_pred = SUP_MODEL.predict([x[:, 0], x[:, 1]]) tpr, fpr, _ = roc_curve(y, model_pred) roc_auc = auc(fpr, tpr) print('auc is : ' + str(roc_auc)) plt.figure(1) plt.plot(fpr, tpr, label='ROC curve (area = %0.2f)' % roc_auc) plt.hold(True) plt.plot([0, 1], [0, 1], 'k--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('ROC curve') plt.legend(loc="lower right") plt.hold(False) plt.savefig('/home/nripesh/Dropbox/temp_images/nnet_train_images/roc_curve_siamese_unsup.png')
def test_on_UNSUP_model(unsup_model_name, x, y, roc_curv_save_name): UNSUP_ENCODER = load_model(unsup_model_name) x_0_encode = UNSUP_ENCODER.predict(x[:, 0, :, 1:, 1:, 1:]) x_1_encode = UNSUP_ENCODER.predict(x[:, 1, :, 1:, 1:, 1:]) # vectorize the matrices x_en_sz = x_0_encode.shape x_0_encode = np.reshape(x_0_encode, (x_en_sz[0], x_en_sz[1] * x_en_sz[2] * x_en_sz[3] * x_en_sz[4])) x_1_encode = np.reshape(x_1_encode, (x_en_sz[0], x_en_sz[1] * x_en_sz[2] * x_en_sz[3] * x_en_sz[4])) model_pred = dist_calc_simple(x_0_encode, x_1_encode) tpr, fpr, _ = roc_curve(y, model_pred) roc_auc = auc(fpr, tpr) print('auc is : ' + str(roc_auc)) # plt.figure(2) # plt.plot(fpr, tpr, label='ROC curve (area = %0.2f)' % roc_auc) # plt.hold(True) # plt.plot([0, 1], [0, 1], 'k--') # plt.xlim([0.0, 1.0]) # plt.ylim([0.0, 1.05]) # plt.xlabel('False Positive Rate') # plt.ylabel('True Positive Rate') # plt.title('ROC curve') # plt.legend(loc="lower right") # plt.hold(False) # plt.savefig('/home/nripesh/Dropbox/temp_images/nnet_train_images/' + roc_curv_save_name + '.png')
def plot_correlations(self, iabscissa=1): """spectrum of correlation matrix and largest correlation""" if not hasattr(self, 'corrspec'): self.load() if len(self.corrspec) < 2: return self x = self.corrspec[:, iabscissa] y = self.corrspec[:, 6:] # principle axes ys = self.corrspec[:, :6] # "special" values from matplotlib.pyplot import semilogy, text, grid, axis, title self._enter_plotting() semilogy(x, y, '-c') # hold(True) semilogy(x[:], np.max(y, 1) / np.min(y, 1), '-r') text(x[-1], np.max(y[-1, :]) / np.min(y[-1, :]), 'axis ratio') if ys is not None: semilogy(x, 1 + ys[:, 2], '-b') text(x[-1], 1 + ys[-1, 2], '1 + min(corr)') semilogy(x, 1 - ys[:, 5], '-b') text(x[-1], 1 - ys[-1, 5], '1 - max(corr)') semilogy(x[:], 1 + ys[:, 3], '-k') text(x[-1], 1 + ys[-1, 3], '1 + max(neg corr)') semilogy(x[:], 1 - ys[:, 4], '-k') text(x[-1], 1 - ys[-1, 4], '1 - min(pos corr)') grid(True) ax = array(axis()) # ax[1] = max(minxend, ax[1]) axis(ax) title('Spectrum (roots) of correlation matrix') # pyplot.xticks(xticklocs) self._xlabel(iabscissa) self._finalize_plotting() return self
def _enter_plotting(self, fontsize=7): """assumes that a figure is open """ from matplotlib import pyplot # interactive_status = matplotlib.is_interactive() self.original_fontsize = pyplot.rcParams['font.size'] # if font size deviates from default, we assume this is on purpose and hence leave it alone if pyplot.rcParams['font.size'] == pyplot.rcParamsDefault['font.size']: pyplot.rcParams['font.size'] = fontsize # was: pyplot.hold(False) # pyplot.gcf().clear() # opens a figure window, if non exists pyplot.ioff()
def plot_and_wait(audio_in,d,col): print "starting plot" plt.xlim([0,4000]); plt.ylim([-1,1]); plt.plot(audio_in, 'r') plt.grid(True) plt.hold(True) plt.plot(d,col) plt.hold(False) plt.draw()
def plot_fft(d): eps = 1e-6 d = abs(fft(d))+eps plt.plot(d,'r') plt.grid(True) plt.hold(False) plt.xlim([0,400]); plt.draw()
def __init__(self, size=(600,350)): streams = resolve_byprop('name', 'bci', timeout=2.5) try: self.inlet = StreamInlet(streams[0]) except IndexError: raise ValueError('Make sure stream name=bci is opened first.') self.running = True self.ProcessedSig = [] self.SecondTimes = [] self.count = -1 self.sampleCount = self.count self.maximum = 0 self.minimum = 0 plt.ion() plt.hold(False) self.lineHandle = plt.plot(self.SecondTimes, self.ProcessedSig) plt.title("Live Stream EEG Data") plt.xlabel('Time (s)') plt.ylabel('mV') #plt.autoscale(True, 'y', tight = True) plt.show() #while(1): #secondTimes.append(serialData[0]) #add time stamps to array 'timeValSeconds' #floatSecondTimes.append(float(serialData[0])/1000000) # makes all second times into float from string #processedSig.append(serialData[6]) #add processed signal values to 'processedSig' #floatProcessedSig.append(float(serialData[6]))
def __init__(self, size=(600,350)): self.running = True self.ProcessedSig = [] self.SecondTimes = [] self.count = -1 plt.ion() plt.hold(False) self.lineHandle = plt.plot(self.SecondTimes, self.ProcessedSig) plt.title("Streaming Live EMG Data") plt.xlabel('Time (s)') plt.ylabel('Volts') plt.show()
def plot_correlations(self, iabscissa=1): """spectrum of correlation matrix and largest correlation""" if not hasattr(self, 'corrspec'): self.load() if len(self.corrspec) < 2: return self x = self.corrspec[:, iabscissa] y = self.corrspec[:, 6:] # principle axes ys = self.corrspec[:, :6] # "special" values from matplotlib.pyplot import semilogy, hold, text, grid, axis, title self._enter_plotting() semilogy(x, y, '-c') hold(True) semilogy(x[:], np.max(y, 1) / np.min(y, 1), '-r') text(x[-1], np.max(y[-1, :]) / np.min(y[-1, :]), 'axis ratio') if ys is not None: semilogy(x, 1 + ys[:, 2], '-b') text(x[-1], 1 + ys[-1, 2], '1 + min(corr)') semilogy(x, 1 - ys[:, 5], '-b') text(x[-1], 1 - ys[-1, 5], '1 - max(corr)') semilogy(x[:], 1 + ys[:, 3], '-k') text(x[-1], 1 + ys[-1, 3], '1 + max(neg corr)') semilogy(x[:], 1 - ys[:, 4], '-k') text(x[-1], 1 - ys[-1, 4], '1 - min(pos corr)') grid(True) ax = array(axis()) # ax[1] = max(minxend, ax[1]) axis(ax) title('Spectrum (roots) of correlation matrix') # pyplot.xticks(xticklocs) self._xlabel(iabscissa) self._finalize_plotting() return self
def _enter_plotting(self, fontsize=9): """assumes that a figure is open """ # interactive_status = matplotlib.is_interactive() self.original_fontsize = pyplot.rcParams['font.size'] pyplot.rcParams['font.size'] = fontsize pyplot.hold(False) # opens a figure window, if non exists pyplot.ioff()
def plot(self, plot_cmd=None, tf=lambda y: y): """plot the data we have, return ``self``""" if not plot_cmd: plot_cmd = self.plot_cmd colors = 'bgrcmyk' pyplot.hold(False) res = self.res flatx, flatf = self.flattened() minf = np.inf for i in flatf: minf = min((minf, min(flatf[i]))) addf = 1e-9 - minf if minf <= 1e-9 else 0 for i in sorted(res.keys()): # we plot not all values here if isinstance(i, int): color = colors[i % len(colors)] arx = sorted(res[i].keys()) plot_cmd(arx, [tf(np.median(res[i][x]) + addf) for x in arx], color + '-') pyplot.text(arx[-1], tf(np.median(res[i][arx[-1]])), i) pyplot.hold(True) plot_cmd(flatx[i], tf(np.array(flatf[i]) + addf), color + 'o') pyplot.ylabel('f + ' + str(addf)) pyplot.draw() pyplot.ion() pyplot.show() # raw_input('press return') return self
def rasta_plp_extractor(x, sr, plp_order=0, do_rasta=True): spec = log_power_spectrum_extractor(x, int(sr*0.02), int(sr*0.01), 'hamming', False) bark_filters = int(np.ceil(freq2bark(sr//2))) wts = get_fft_bark_mat(sr, int(sr*0.02), bark_filters) ''' plt.figure() plt.subplot(211) plt.imshow(wts) plt.subplot(212) plt.hold(True) for i in range(18): plt.plot(wts[i, :]) plt.show() ''' bark_spec = np.matmul(wts, spec) if do_rasta: bark_spec = np.where(bark_spec == 0.0, np.finfo(float).eps, bark_spec) log_bark_spec = np.log(bark_spec) rasta_log_bark_spec = rasta_filt(log_bark_spec) bark_spec = np.exp(rasta_log_bark_spec) post_spec = postaud(bark_spec, sr/2.) if plp_order > 0: lpcas = do_lpc(post_spec, plp_order) # lpcas = do_lpc(spec, plp_order) # just for test else: lpcas = post_spec return lpcas
def plotDGMAx(ax, dgm, color = 'b', sz = 20, label = 'dgm'): if dgm.size == 0: return axMin = np.min(dgm) axMax = np.max(dgm) axRange = axMax-axMin; ax.scatter(dgm[:, 0], dgm[:, 1], sz, color,label=label) ax.hold(True) ax.plot([axMin-axRange/5,axMax+axRange/5], [axMin-axRange/5, axMax+axRange/5],'k'); ax.set_xlabel('Time of Birth') ax.set_ylabel('Time of Death')
def plot2DGMs(P1, P2, l1 = 'Diagram 1', l2 = 'Diagram 2'): plotDGM(P1, 'r', 10, label = l1) plt.hold(True) plt.plot(P2[:, 0], P2[:, 1], 'bx', label = l2) plt.legend() plt.xlabel("Birth Time") plt.ylabel("Death Time")
def plotTriangles(X, A, B, C): plt.hold(True) ax = plt.gca() for i in range(len(A)): poly = [X[A[i], :], X[B[i], :], X[C[i], :]] ax.add_patch(Polygon(np.array(poly), linestyle='solid', color='#00FF00', alpha=0.05))
def plot_gpx_route(lon, lat, title): fig = plt.figure(facecolor='0.05') ax = plt.Axes(fig, [0., 0., 1., 1.], ) ax.set_aspect(1.2) ax.set_axis_off() ax.set_title(title, color='white', fontsize=15) fig.add_axes(ax) plt.plot(lon, lat, '+-', color='red', lw=1, alpha=1) plt.hold(True) return plt