def scatter_plot(P, L, pcIdx1, pcIdx2, letterList, rev): fig = plt.figure() # following the convention in lecture note ScatterPlot.html colors = ["r", "lime", "b", "y", "c", "m", "k", "tan", "pink", "darkred"] for i, letter in enumerate(letterList): plt.scatter(P[L == letter, pcIdx2], P[L == letter, pcIdx1], s=0.1, c=colors[i], label=letter) plt.axes().set_aspect('equal') #plt.axes().set_aspect('equal', 'datalim') plt.xlabel("Principle Component {}".format(pcIdx2)) plt.ylabel("Principle Component {}".format(pcIdx1)) plt.axhline(0, color='grey') plt.axvline(0, color='grey') plt.ylim([-5000, 5000]) plt.xlim([-5000, 5000]) plt.legend() plt.gca().invert_yaxis() fig.set_size_inches(8, 8) fName = os.path.join( pDir, 'scatter_PC{}_PC{}_{}_{}.png'.format(pcIdx1, pcIdx2, "".join(letterList), rev)) savefig(fName, bbox_inches='tight') plt.show()
def write_pc_hist(df, p, args): # Pivot, and then drop the "cycles" level of the multi-index. df = pd.pivot_table(df, index=["pc"], columns="operation") df = df.fillna(0) df = df.droplevel(level=0, axis="columns") # Use the colors key order above to stack the bars, # but first we have to pick stalls that are actually IN the CSV (not all are printed) cols = [k for k in colors.keys() if k in df.columns] df = df[cols] # Remove all PCs that were specified using the without flag filts = {int(pc, 16) for pc in args.without} fi = [pc for pc in df.index if int(pc, 16) not in filts] removed = [pc for pc in df.index if int(pc, 16) in filts] df = df.loc[fi] print(f"Removed PCs: {removed}") height = df.shape[0] * (labelsize + 4) / 72 ax = df.plot.barh(stacked=True, figsize=(11, height), color=colors) ax.set_ylabel("Program Counter") ax.set_xlabel(f"Cycles * 10^{math.floor(math.log10(ax.get_xlim()[1]))}") ax.set_title(f"HammerBlade Program Counter Cycles Histogram") ax.tick_params(labelsize=labelsize) fig = ax.get_figure() plt.gca().invert_yaxis() plt.legend(loc="upper left") plt.tight_layout() fig.savefig(p / "pc_hist.pdf") plt.close(fig)
def show_spearman_hm(): if len(X_train): plot_corr_heatmap(X_train, figsize=(12, 10)) plt.gca().set_aspect('auto') a = plt.gca() a.set_title('Spearman rank correlation coefficients heatmap') a.get_figure().canvas.set_window_title('corr') plt.show()
def write_bb_hist(df, p, args): # Pivot, and then drop the "cycles" level of the multi-index. df = pd.pivot_table(df, index=["pc"], columns="operation") df = df.fillna(0) df = df.droplevel(level=0, axis="columns") # Group together floating point and regular instructionos tot_instrs = df.Instruction + df["FPU Instruction"] # Group together PCs that have the same number of executions bb_ranges = (tot_instrs != tot_instrs.shift()).cumsum() df = df.groupby(bb_ranges).sum() # Get the new grouped index bb_tups = [(bb_ranges[bb_ranges == x].index.min(), bb_ranges[bb_ranges == x].index.max()) for x in df.index] bb_ranges = [range(int(x, 16), int(y, 16) + 1) for (x, y) in bb_tups] # Filter BBs that include PCs that were specified with --without filts = {int(pc, 16) for pc in args.without} df.index = [x + "-" + y for (x, y) in bb_tups] fi = [ x + "-" + y for (x, y) in bb_tups if (all(e not in range(int(x, 16), int(y, 16) + 1) for e in filts)) ] removed = [ x + "-" + y for (x, y) in bb_tups if (any(e in range(int(x, 16), int(y, 16) + 1) for e in filts)) ] # TODO: Print filtered BBs on graph? print(f"Removed Basic Blocks: {removed}") df = df.loc[fi] ipc = (df.Instruction + df["FPU Instruction"]) / df.sum(axis=1) pct = 100.0 * df.sum(axis=1) / df.sum(axis=1).sum() idx = df.index.to_series() idx = idx.combine(pct, lambda i, pct: f"{i} ({pct:.0f}%".rjust(10)) idx = idx.combine(ipc, (lambda i, ipc: f"{i} @ {ipc:1.3f})")) df.index = idx # Use the colors key order above to stack the bars, # but first we have to pick stalls that are actually IN the CSV (not all are printed) cols = [k for k in colors.keys() if k in df.columns] height = df.shape[0] * (labelsize + 4) / 72 ax = df[cols].plot.barh(stacked=True, figsize=(11, height), color=colors) ax.set_ylabel("Basic Block Range (% Cycles @ IPC)") ax.set_xlabel(f"Cycles * 10^{math.floor(math.log10(ax.get_xlim()[1]))}") ax.set_title(f"HammerBlade Basic Block Cycles Histogram") ax.tick_params(labelsize=labelsize) fig = ax.get_figure() plt.gca().invert_yaxis() plt.legend(loc="upper right") plt.tight_layout() fig.savefig(p / "bb_hist.pdf") plt.close(fig)
def draw_boxes_on_image(image_path: str, boxes: np.ndarray, scores: np.ndarray, labels: np.ndarray, label_names: List[str], score_thresh: float = 0.5, save_path: str = 'result'): """Draw boxes on images.""" image = np.array(PIL.Image.open(image_path)) plt.figure() _, ax = plt.subplots(1) ax.imshow(image) image_name = image_path.split('/')[-1] print("Image {} detect: ".format(image_name)) colors = {} for box, score, label in zip(boxes, scores, labels): if score < score_thresh: continue if box[2] <= box[0] or box[3] <= box[1]: continue label = int(label) if label not in colors: colors[label] = plt.get_cmap('hsv')(label / len(label_names)) x1, y1, x2, y2 = box[0], box[1], box[2], box[3] rect = plt.Rectangle((x1, y1), x2 - x1, y2 - y1, fill=False, linewidth=2.0, edgecolor=colors[label]) ax.add_patch(rect) ax.text(x1, y1, '{} {:.4f}'.format(label_names[label], score), verticalalignment='bottom', horizontalalignment='left', bbox={ 'facecolor': colors[label], 'alpha': 0.5, 'pad': 0 }, fontsize=8, color='white') print("\t {:15s} at {:25} score: {:.5f}".format( label_names[int(label)], str(list(map(int, list(box)))), score)) image_name = image_name.replace('jpg', 'png') plt.axis('off') plt.gca().xaxis.set_major_locator(plt.NullLocator()) plt.gca().yaxis.set_major_locator(plt.NullLocator()) plt.savefig("{}/{}".format(save_path, image_name), bbox_inches='tight', pad_inches=0.0) plt.cla() plt.close('all')
def display_image(originalImage, imageWithPath, algorithmType): """ Display the original image and the image with path side by side :param originalImage: The original image with pixel densities :param imageWithPath: The image with the best path using the specified method :param algorithmType: The selected algorithm type """ plt.subplot(1, 2, 1) plt.gca().set_title('Original') plt.imshow(originalImage) plt.subplot(1, 2, 2) plt.gca().set_title("Best Path: " + algorithmType.value) plt.imshow(imageWithPath) plt.show()
def plot_everything_scenario_invertitoKM(): num_plots = 6 colormap = plt.cm.gist_ncar plt.gca().set_prop_cycle( plt.cycler('color', plt.cm.jet(np.linspace(0, 1, num_plots)))) meanResponseTime = [] index = [] for k in interarrival_time: index.append("k=" + str(k)) dataframe = pd.DataFrame() dataframe['file'] = index for mode in modes: for m in monitoring_time: meanResponseTime.clear() for i in interarrival_time: if mode == 'Nonmonitoring-exponential-' or mode == 'Nonmonitoring-lognormal-': filename = './csv/pool_max_40000/' + mode + str(i) + '.csv' else: filename = './csv/pool_max_40000/' + mode + str( i) + "," + str(m) + '.csv' with open(filename, 'r') as f: df = scalar_df_parse(filename) df = df[df.name == 'responseTime'] del df['run'] meanResponseTime.append(df.value.mean()) dataframe[f'm={m}'] = meanResponseTime plt.plot(dataframe[f'm={m}'], ":o", label=f"m={m}") plt.xticks([k for k in range(len(index))], [k for k in index]) var = mode.split('-')[0] var2 = mode.split('-')[1] plt.title("scenario: " + var + " " + var2) plt.xticks(rotation=25) plt.xlabel("Value of k") plt.ylabel("Response time") plt.legend(loc='upper left') plt.savefig( f"./analysis/immagini per clarissa/pool_40000/responseTime/invertitiKM/{var}{var2}.png" ) plt.show()
def plot_depiction_communities(self,community_partition,ax=None,radius=1.0,xr=0,yr=0,zr=0,R=10.0): ''' depiction communities by different color and size circles, one could use radius, xr, yr, zr, R parameters to adjust the angle of view ----------------------------------------- community_partition: { int } the partition index, could select with the maximum modularity score index ax: { matplotlib.axes._subplots.AxesSubplot } optional,default = None radius: { float } optional, default = 1.0 the base size of circles. xr,yr,zr: { float } optional, default = 0 the angle for rotation in x y z axis, in radian unit R: { float } optional,default = 10.0 the distance of view ''' community_xy,community_r = self._depiction_communities_position(community_partition,radius,xr,yr,zr,R) if ax == None: fig = plt.figure(figsize=(6,6)) ax = plt.gca() community_correlate = self._community_correlation(community_partition) for i in range(len(community_xy)-1): for j in range(i,len(community_xy)): corr = abs(community_correlate[i][j]) line = [community_xy[i], community_xy[j]] (line_xs, line_ys) = zip(*line) #ax.add_line(Line2D(line_xs, line_ys, linewidth=corr, color='gray',alpha=0.5)) ax.plot(line_xs, line_ys,lw=corr,color='gray',alpha=0.5) for i,r in enumerate(community_r): ax.add_patch(plt.patches.Circle(xy=community_xy[i],radius=r,color=self.colors[i],zorder=i+10)) plt.pyplot.axis('scaled') plt.pyplot.axis('equal')
def plot_lcurve(self, ax=None, guides=True): """ Make a plot of the data-misfit x regularization values. The estimated corner value is shown as a blue triangle. Parameters: * ax : matplotlib Axes If not ``None``, will plot the curve on this Axes instance. * guides : True or False Plot vertical and horizontal lines across the corner value. """ if ax is None: ax = mpl.gca() else: mpl.sca(ax) x, y = self.dnorm, self.mnorm if self.loglog: mpl.loglog(x, y, '.-k') else: mpl.plot(x, y, '.-k') if guides: vmin, vmax = ax.get_ybound() mpl.vlines(x[self.corner_], vmin, vmax) vmin, vmax = ax.get_xbound() mpl.hlines(y[self.corner_], vmin, vmax) mpl.plot(x[self.corner_], y[self.corner_], '^b', markersize=10) mpl.xlabel('Data misfit') mpl.ylabel('Regularization')
def networkx_plot_measure(self, measure: str, draw_node_names = True, draw_graphweights: bool = True, draw_edges: bool = False): """ Plots all specimens of the main dict. A measure is selected for the edge weights. Graphvis tries to get the optimal arrangement based on weights, hard to do for 2d space. Use dot, neato and fdp seem to maximize distances and just create a circular arrangement. :param measure: distance measure for the edges :return: None """ import networkx as nx from networkx.drawing.nx_agraph import graphviz_layout import matplotlib.pyplot as plt dist_matrix_dict = utils.dict_of_dicts_matrix_measure(data_dict=self.data_dict, measure=measure) print("dist_matrix_dict", dist_matrix_dict) G = nx.from_dict_of_dicts(d=dist_matrix_dict) G.graph['edges']={'arrowsize':'4.0'} # neato, fdp seem to mazimize --> circle shape # dot works best, however, 2d representation is difficult pos = graphviz_layout(G, prog="fdp") if draw_edges: nx.draw_networkx(G, pos=pos) else: nx.draw_networkx_nodes(G, pos=pos) if draw_graphweights: nx.draw_networkx_edge_labels(G, pos=pos) if draw_node_names: nx.draw_networkx_labels(G, pos) plt.tight_layout() # adjust the [x, y] values for fitting all the text axes = plt.gca() #axes.set_xlim([-60, 800]) # use these to turn off axis for plotting #plt.xticks([]) #plt.yticks([]) plt.show()
def arrowed_spines(ax=None, arrow_length=20, labels=('', ''), arrowprops=None): xlabel, ylabel = labels if ax is None: ax = plt.gca() if arrowprops is None: arrowprops = dict(arrowstyle='<|-', facecolor='black') for i, spine in enumerate(['left', 'bottom']): # Set up the annotation parameters t = ax.spines[spine].get_transform() xy, xycoords = [1, 0], ('axes fraction', t) xytext, textcoords = [arrow_length, 0], ('offset points', t) ha, va = 'left', 'bottom' # If axis is reversed, draw the arrow the other way top, bottom = ax.spines[spine].axis.get_view_interval() if top > bottom: xy[0] = 0 xytext[0] *= -1 ha, va = 'right', 'top' if spine is 'bottom': xarrow = ax.annotate(xlabel, xy, xycoords=xycoords, xytext=xytext, textcoords=textcoords, ha=ha, va='center', arrowprops=arrowprops) else: yarrow = ax.annotate(ylabel, xy[::-1], xycoords=xycoords[::-1], xytext=xytext[::-1], textcoords=textcoords[::-1], ha='center', va=va, arrowprops=arrowprops) return xarrow, yarrow # lines
def plot_results(pil_img, prob, boxes, classIDs, Name_model = 'DeTr', Save_Images = True, image_name='test', inferene_time = None): if Save_Images : os.makedirs(Name_model,exist_ok=True) plt.figure(figsize=(16,10)) plt.imshow(pil_img) ax = plt.gca() ###################### if len(idxs) > 0: # loop over the indexes we are keeping for i in idxs.flatten(): (x, y) = (boxes[i][0], boxes[i][1]) (w, h) = (boxes[i][2], boxes[i][3]) # draw a bounding box rectangle and label on the image color = [int(c) for c in COLORS[classIDs[i]]] cv2.rectangle(image, (x, y), (x + w, y + h), color, 2) text = "{}: {:.4f}".format(LABELS[classIDs[i]], prob[i]) print(text) #print(str(LABELS[classIDs[i]]) + ' : ' + str(confidences[i])) cv2.putText(image, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 1) cv2.putText(image, f"inference time : {inferene_time:0.2f}", (10, 15), cv2.FONT_HERSHEY_SIMPLEX, 0.5, [0,0,255], 1) cv2.putText(image, f"Number Objects : {len(idxs)}", (10, 25 +30), cv2.FONT_HERSHEY_SIMPLEX, 0.5, [0,0,255], 1) # plt.axis('off') if Save_Images : addr_image = os.path.join(Name_model,image_name) cv2.imwrite(addr_image, image) else: cv2.imshow(f'image_name', image) cv2.waitKey(0)
def draw_in_matplotlib(self, **kwargs): if not kwargs.get('axes'): axes = plt.gca() else: axes = kwargs['axes'] options = dict(self.options) axes.plot(*self.as_axes, **options)
def graficolog(): ax = plt.gca() ax.set_yscale('log') plt.plot(k, eff, 'go') plt.plot(k, eaf, 'ro') plt.plot(k, ebf, 'bo') plt.grid(True) plt.show()
def cases_deaths(df): df.assign(dummy=1).groupby(['dummy', 'cases']).size().groupby( level=0).apply(lambda x: 100 * x / x.sum()).to_frame().unstack().plot( kind='bar', stacked=True, legend=False) # or it'll show up as 'dummy' plt.xlabel('cases') # disable ticks in the x axis plt.xticks([]) # fix the legend or it'll include the dummy variable current_handles, _ = plt.gca().get_legend_handles_labels() reversed_handles = reversed(current_handles) correct_labels = reversed(df['cases'].unique()) ax = plt.gca() df.plot(kind='line', x='month', y='deaths', ax=ax) df.plot(kind='line', x='month', y='cases', color='red', ax=ax) plt.show()
def stacked_deaths(df): df.assign(dummy=1).groupby(['dummy', 'deaths']).size().groupby( level=0).apply(lambda x: 100 * x / x.sum()).to_frame().unstack().plot( kind='bar', stacked=True, legend=False) # or it'll show up as 'dummy' plt.xlabel('deaths') # disable ticks in the x axis plt.xticks([]) # fix the legend or it'll include the dummy variable current_handles, _ = plt.gca().get_legend_handles_labels() reversed_handles = reversed(current_handles) correct_labels = reversed(df['deaths'].unique()) plt.legend(reversed_handles, correct_labels) plt.gca().yaxis.set_major_formatter(mtick.PercentFormatter()) plt.show()
def checkCircle(data): import matplotlib as plot # Transform data by rotation so that all data appears in the firt and # second quadrants (so that positive square root solution is valid) rot = np.arctan2(data[-1, 1] - data[0, 1], data[-1, 0] - data[0, 0]) R = getRotMat(rot + np.pi) trans = np.matmul(data, R) trans[:, 1] *= -1 # Display transformed data used for the actual fit plot.figure(2) plot.clf() plot.plot(trans[:, 0], trans[:, 1], '*') plot.axis("equal") thresh = 0.01 E = 10 count = 0 # Perform gradient descent up to four times with slightly different guesses # until a low E solution is found. while E > thresh and count < 4: count += 1 xBar = np.mean(trans[:, 0]) * (0.95 + np.random.rand(1) * 0.1)[0] yBar = np.min(trans[:, 1]) * (0.95 + np.random.rand(1) * 0.1)[0] rBar = np.abs((trans[0, 0] - trans[-1, 0]) / 2) * (0.95 + np.random.rand(1) * 0.1)[0] x0, y0, r, E = descent(trans, xBar, yBar, rBar) print(E) # More plotting of transformed data circle = plot.Circle((x0, y0), r, color='r', fill=False) plot.gca().add_artist(circle) # Rotate back to original coordinates y0 *= -1 center = np.matmul([x0, y0], np.linalg.inv(R)) if E < thresh: return center, r else: return None, None
def rfpimp_dropc(rf, x, y, naslov): if len(x): fig3 = plt.figure() imp = dropcol_importances(rf, x, y) # drop columns r = 'Drop-column feature importances:\n%s' % '\n'.join( ['%s %s' % (c[0], c[1].Importance) for c in imp.iterrows()]) app.mText.insert('end-1c', '%s\n' % r) viz = plot_importances(imp) # viz.view() a = plt.gca() a.set_title('Drop-column importances') a.get_figure().canvas.set_window_title(naslov) plt.show()
def rfpimp_imp(rf, x, y, naslov): if len(x): fig2 = plt.figure() imp = importances(rf, x, y) # permutation r = 'Permutation feature importances:\n%s' % \ '\n'.join(['%s %s' % (c[0], c[1].Importance) for c in imp.iterrows()]) app.mText.insert('end-1c', '%s\n' % r) viz = plot_importances(imp) # viz.view() a = plt.gca() a.set_title('Permutation importances') a.get_figure().canvas.set_window_title(naslov) plt.show()
def grafico(h, vtsaf, cor): ax = plt.gca() # gca stands for 'get current axis' ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') ax.spines['bottom'].set_position(('data', 0)) ax.yaxis.set_ticks_position('left') ax.spines['left'].set_position(('data', 0)) plt.plot(X, vf(X), '-r', label='f(x)') plt.plot(X, vtsaf(X), cor, label='Derivada atrasada') plt.grid(True) plt.show()
def show_feature_dep_matrix(): if len(X_train): # Feature dependence matrix d = feature_dependence_matrix(X_train) pd.set_option('precision', 3) r = d['Dependence'].sort_values(ascending=False) app.mText.insert('end-1c', '%s\n' % r) viz = plot_dependence_heatmap(d, figsize=(11, 10)) # viz.show() a = plt.gca() a.set_title('Feature dependence matrix') a.get_figure().canvas.set_window_title('corr_dep') plt.show()
def draw(self): if self.plot_h['axis'] is None: #self.plot_h['fig'] = plt.figure() plt.figure() self.grid.drawGrid() self.plot_h['axis'] = plt.gca() self.plot_h['axis'].set_aspect(1) else: plt.sca(self.plot_h['axis']) for vox in self.voxels: vox.draw() if Par.liveDrawing: plt.pause(1e-6)
def udaljenost_tocke(x1,y1,x2,y2,r): plt.xlim([0,10]) plt.ylim([0,10]) kruznica = plt.Circle((x2,y2),r,color='r') plt.gca().add_artist(kruznica) plt.plot(x1,y1, 'bo') x = (x1-x2)**2 + (y1-y2)**2 d = sqrt(x) nacin = int(input('Unesi 1 za prikaz slike, 2 za spremanje')) if znak ==1: plt.show() elif znak ==2: naziv = input('Unesite naziv slike:') plt.savefig(f'{naziv}.pdf') epsilon = 0.01 if d < r: print(f'Točka je unutar kružnice, a udaljenost je {d}.') elif r-epsilon < d < r+epsilon: print(f'Točka se nalazi na kružnici.') else: print(f'Točka je izvan kružnice, a udaljenost je {d}.')
def draw_scatter_plot(cloud_a, cloud_b, xp, xn, all_labels): log("\nPC Scatter Plot: {}, {}!".format(xp, xn)) #if not ENABLE_IMAGE_SHOW: # return fig = plt.figure() cols = np.zeros((alen(all_labels), 4)) for idx, ll in enumerate(all_labels): if ll == POSITIVE_CLASS: cols[idx] = [1, 0, 0, SCATTER_PLOT_ALPHA] if ll == NEGATIVE_CLASS: cols[idx] = [0, 0.2, 1, SCATTER_PLOT_ALPHA] random_order = np.arange(np.alen(all_labels)) ax = fig.add_subplot(111, facecolor='white') ax.scatter(cloud_b, cloud_a, s=8, linewidths=0, facecolors=cols[random_order, :], marker='o') ax.plot(xp[1], xp[0], marker='x', color='black', label='XP[{}]'.format(POSITIVE_CLASS)) ax.plot(xn[1], xn[0], marker='*', color='black', label='XN[{}]'.format(NEGATIVE_CLASS)) ax.legend(loc='lower left', numpoints=1, ncol=3, fontsize=10, bbox_to_anchor=(0, 0)) ax.set_aspect('equal') plt.rcParams['axes.facecolor'] = 'b' plt.gca().invert_yaxis() plt.title('Principal Components PC1 and PC2 scatter plot\nManoj Govindassamy') plt.show()
def get_trajectories_for_DF(DF): GetXYS=ct.get_xys(DF) xys_s=ct.get_xys_s(GetXYS['xys'],GetXYS['Nmin']) plt.figure(figsize=(5, 5),frameon=False) for m in list(range(9)): plt.plot() plt.subplot(3,3,m+1) xys_s_x_n=xys_s[m]['X']-min(xys_s[m]['X']) xys_s_y_n=xys_s[m]['Y']-min(xys_s[m]['Y']) plt.plot(xys_s_x_n,xys_s_y_n) plt.axis('off') axes = plt.gca() axes.set_ylim([0,125]) axes.set_xlim([0,125])
def OnMouseMotion(event): global Coords2x,Coords2y,x1,y1 if event.button == 1: Coords2x = event.xdata Coords2y = event.ydata x1 = [Coords1x,Coords2x] y1 = [Coords1y,Coords2y] ax = plt.gca() lines = ax.plot(x1,y1,picker = 20) ax.figure.canvas.draw() l = lines.pop(0) l.remove() del l elif event.button == 3: Coords4x = event.xdata Coords4y = event.ydata x2 = [Coords3x,Coords4x] y2 = [Coords3y,Coords4y] ax1 = plt.gca() lines1 = ax1.plot(x2,y2,picker = 20) ax1.figure.canvas.draw() l = lines1.pop(0) l.remove() del l
def Gershgorin(self): if is_square(self.x) != True: print('Please enter a square matrix') return [] else: row_sum = [] list_diagonals = [] list_diagonals.append(np.array(self.x).diagonal()) self.x = np.absolute(self.x) row_sum.append( np.array(self.x).sum(axis=1) - np.array(self.x).diagonal()) y, z = row_sum, list_diagonals z = np.array(z).tolist() y = np.array(y).tolist() circles = list(map(list, zip(z[0], y[0]))) index, radi = zip(*circles) Xupper = max(index) + np.std(index) Xlower = min(index) - np.std(index) Ylimit = max(radi) + np.std(index) fig, ax = plt.subplots() ax = plt.gca() ax.cla() ax.set_xlim((Xlower, Xupper)) ax.set_ylim((-Ylimit, Ylimit)) plt.xlabel('Real Axis') plt.ylabel('Imaginary Axis') plt.title('Gershgorin circles') for x in range(0, len(circles)): circ = plt.Circle((index[x], 0), radius=radi[x]) ax.add_artist(circ) ax.plot([Xlower, Xupper], [0, 0], 'k--') ax.plot([0, 0], [-Ylimit, Ylimit], 'k--') ax.yaxis.grid(True, linestyle="--") ax.xaxis.grid(True, linestyle="--") for i in index: plt.axvline(x=i, linestyle='--', color='r') # vertical lines plt.show()
def arrowed_spines(ax=None, arrow_length=20, labels=("", ""), arrowprops=None): xlabel, ylabel = labels if ax is None: ax = plt.gca() if arrowprops is None: arrowprops = dict(arrowstyle="<|-", facecolor="black") for i, spine in enumerate(["left", "bottom"]): # Set up the annotation parameters t = ax.spines[spine].get_transform() xy, xycoords = [1, 0], ("axes fraction", t) xytext, textcoords = [arrow_length, 0], ("offset points", t) ha, va = "left", "bottom" # If axis is reversed, draw the arrow the other way top, bottom = ax.spines[spine].axis.get_view_interval() if top > bottom: xy[0] = 0 xytext[0] *= -1 ha, va = "right", "top" if spine is "bottom": xarrow = ax.annotate( xlabel, xy, xycoords=xycoords, xytext=xytext, textcoords=textcoords, ha=ha, va="center", arrowprops=arrowprops, ) else: yarrow = ax.annotate( ylabel, xy[::-1], xycoords=xycoords[::-1], xytext=xytext[::-1], textcoords=textcoords[::-1], ha="center", va=va, arrowprops=arrowprops, ) return xarrow, yarrow # lines
def fill_between_steps(x, y1, y2=0, h_align='mid', ax=None, **kwargs): ''' Fills a hole in matplotlib: fill_between for step plots. Parameters : ------------ x : array-like Array/vector of index values. These are assumed to be equally-spaced. If not, the result will probably look weird... y1 : array-like Array/vector of values to be filled under. y2 : array-Like Array/vector or bottom values for filled area. Default is 0. **kwargs will be passed to the matplotlib fill_between() function. ''' # If no Axes opject given, grab the current one: if ax is None: ax = plt.gca() # First, duplicate the x values xx = x.repeat(2)[1:] # Now: the average x binwidth xstep = np.repeat((x[1:] - x[:-1]), 2) xstep = np.concatenate(([xstep[0]], xstep, [xstep[-1]])) # Now: add one step at end of row. xx = np.append(xx, xx.max() + xstep[-1]) # Make it possible to chenge step alignment. if h_align == 'mid': xx -= xstep / 2. elif h_align == 'right': xx -= xstep # Also, duplicate each y coordinate in both arrays y1 = y1.repeat(2)#[:-1] if type(y2) == np.ndarray: y2 = y2.repeat(2)#[:-1] # now to the plotting part: ax.fill_between(xx, y1, y2=y2, **kwargs) return ax
def checkOverlap(flag, n, a1, b1, a2, b2): ## Generate the sets of points and find their hulls if flag: setA = generateUniform(n, a1, b1) setB = generateUniform(n, a2, b2) else: setA = generateNormal(n, a1, b1) setB = generateNormal(n, a2, b2) hullA = jarvisMarch(setA) hullB = jarvisMarch(setB) ## Do all the plotting setAx, setAy = extractCoords(setA) setBx, setBy = extractCoords(setB) hullAx, hullAy = extractCoords(hullA) hullBx, hullBy = extractCoords(hullB) plt.plot(setAx, setAy, 'b.') plt.plot(setBx, setBy, 'c.') plt.plot(hullAx, hullAy, 'ro') plt.plot(hullBx, hullBy, 'mo') ## Approximate the centers of the hulls centerA = (avg(hullAx), avg(hullAy)) centerB = (avg(hullBx), avg(hullBy)) ## Find the maximum radii of the hulls and add the bounding ## circles to the plot rA = radius(centerA, hullA) rB = radius(centerB, hullB) circleA = plt.Circle(centerA, rA, color='r', fill=False) circleB = plt.Circle(centerB, rB, color='m', fill=False) ax = plt.gca() ax.add_patch(circleA) ax.add_patch(circleB) plt.axis('scaled') plt.show() ## If the distance between the centers is less than the sum ## of the radii the circles overlap if rA + rB >= dist(centerA, centerB): return 1 return 0
#36 ss.add_element(location=[[9.9, 1.5], [10.5, 0.7]]) #37 ss.add_element(location=[[10.5, 0.7], [11, 1.1]]) #38 ss.add_element(location=[[10.5, 1.2], [11, 1.1]]) #39 ss.add_element(location=[[9.9, 2.6], [11, 1.1]]) #40 ss.add_element(location=[[10.5, 0.7], [11.5, 0]]) #41 ss.add_element(location=[[11, 1.1], [11.5, 0]]) #supports and loads ss.add_support_fixed(node_id=[1]) ss.point_load(10, Fx=10, rotation=90) ss.add_support_fixed(node_id=ss.id_last_node) #ss.q_load(q=-20, element_id=23, direction='element') #ss.q_load(q=-20, element_id=16, direction='element') #ss.q_load(q=-20, element_id=13, direction='element') #ss.q_load(q=-20, element_id=28, direction='element') ss.show_structure() ss.solve() #ss.show_bending_moment() ss.show_displacement() #ss.show_reaction_force() #ss.show_shear_force() plt.gca() line = ax.lines[0] line.get_xydata()
# print(x_axis_data) y_axis_data1 = pred y = [0, 1, 2, 3, 4] # plt.figure(dpi=200) plt.figure(figsize=(26, 8)) # plt.scatter(x_axis_data, pred, marker='x', color='red', s=40, label='predict') # plt.scatter(x_axis_data, lable, marker = 'x', color = 'blue', s = 40, label = 'Second') # plt.legend(loc='best') # plt.show() # plt.savefig("/opt/data/private/new/pythoncode/picture/sdtgru1082.svg") # plot中参数的含义分别是横轴值,纵轴值,线的形状,颜色,透明度,线的宽度和标签 # plt.plot(x_axis_data, y_axis_data1, 'r-', color='blue', alpha=1, linewidth=1,label='predict') # plt.plot(x_axis_data, lable, 'r-', color='red', alpha=1, linewidth=1, label='lable') # 显示标签,如果不加这句,即使在plot中加了label='一些数字'的参数,最终还是不会显示标签 plt.legend(loc="upper right") plt.xlabel('Time') # plt.ylabel('accuracy') plt.xticks(x) plt.yticks(y, ('Wake', 'N1', 'N2', 'N3', 'REM')) plt.tick_params(labelsize=16) ax = plt.gca() ax.spines['bottom'].set_linewidth(2) ax.spines['left'].set_linewidth(2) accuracy = accuracy_score(lable, pred) print(accuracy) plt.show() plt.savefig(savepath + "grucrf" + str(num) + ".svg")
def create_figure_surface(figid, aspect, xx, yy, cmin, cmax, levels, slices, v3d): ''' creates a plot of the surface of a tracer data Parameters ---------- figid : int id of figure aspect: float aspect ratio of figure xx : array scale of x axis yy : array scale of y axis cmin,cmax : array minimum and maxminm of the color range levels : array range of contourlines slices : array location of slices v3d : vector data in geometry format Returns ------- plot : of surface data ''' # prepare matplotlib import matplotlib matplotlib.rc("font",**{"family":"sans-serif"}) matplotlib.rc("text", usetex=True) #matplotlib.use("PDF") import matplotlib.pyplot as plt # basemap from mpl_toolkits.basemap import Basemap # numpy import numpy as np # data vv = v3d[0,:,:,0] # shift vv = np.roll(vv, 64, axis=1) # plot surface plt.figure(figid) # colormap cmap = plt.cm.bone_r # contour fill p1 = plt.contourf(xx, yy, vv, cmap=cmap, levels=levels, origin="lower")#, hold="on") plt.clim(cmin, cmax) # contour lines p2 = plt.contour(xx, yy, vv, levels=levels, linewidths = (1,), colors="k")#, hold="on") plt.clabel(p2, fmt = "%2.1f", colors = "k", fontsize = 14) #plt.colorbar(p2,shrink=0.8, extend='both') # slices #s1 = xx[np.mod(slices[0]+64, 128)] #s2 = xx[np.mod(slices[1]+64, 128)] #s3 = xx[np.mod(slices[2]+64, 128)] # print s1, s2, s3 #plt.vlines([s1, s2, s3], -90, 90, color='k', linestyles='--') # set aspect ratio of axes plt.gca().set_aspect(aspect) # basemap m = Basemap(projection="cyl") m.drawcoastlines(linewidth = 0.5) # xticks plt.xticks(range(-180, 181, 45), range(-180, 181, 45)) plt.xlim([-180, 180]) plt.xlabel("Longitude [degrees]", labelpad=8) # yticks plt.yticks(range(-90, 91, 30), range(-90, 91, 30)) plt.ylim([-90, 90]) plt.ylabel("Latitude [degrees]") # write to file plt.savefig("solution-surface", bbox_inches="tight") plt.show()
# In[10]: from matplotlib import pyplot as plt # In[11]: #ploting figure fig = plt.figure(figsize=(15,12)) plt.suptitle('Histograms of Numerical Columns', fontsize=20) for i in range(1,dataset2.shape[1]+1): plt.subplot(6,5,i) f=plt.gca() f.axes.get_yaxis().set_visible(False) f.set_title(dataset2.columns.values[i-1]) vals=np.size(dataset2.iloc[:,i-1].unique()) plt.hist(dataset2.iloc[:,i-1],bins=vals,color='#3F5D7D') plt.tight_layout(rect=[0,0.03,1,0.95]) # In[12]: #piechart plots dataset2=dataset[['housing','is_referred','app_downloaded','web_user', 'app_web_user', 'ios_user', 'android_user', 'registered_phones', 'payment_type', 'waiting_4_loan', 'cancelled_loan', 'received_loan', 'rejected_loan', 'zodiac_sign', 'left_for_two_month_plus', 'left_for_one_month', 'is_referred']]
P[0] = 1.0 for k in range(1,n_iter): # time update xhatminus[k] = xhat[k-1] Pminus[k] = P[k-1]+Q # measurement update K[k] = Pminus[k]/( Pminus[k]+R ) xhat[k] = xhatminus[k]+K[k]*(z[k]-xhatminus[k]) P[k] = (1-K[k])*Pminus[k] plt.pyplot.figure() plt.pyplot.plot(z,'k+',label='noisy measurements') plt.pyplot.plot(xhat,'b-',label='a posteri estimate') plt.pyplot.axhline(x,color='g',label='truth value') plt.pyplot.legend() plt.pyplot.title('Estimate vs. iteration step', fontweight='bold') plt.pyplot.xlabel('Iteration') plt.pyplot.ylabel('Voltage') plt.pyplot.figure() valid_iter = range(1,n_iter) # Pminus not valid at step 0 plt.pyplot.plot(valid_iter,Pminus[valid_iter],label='a priori error estimate') plt.pyplot.title('Estimated $\it{\mathbf{a \ priori}}$ error vs. iteration step', fontweight='bold') plt.pyplot.xlabel('Iteration') plt.pyplot.ylabel('$(Voltage)^2$') plt.pyplot.setp(plt.gca(),'ylim',[0,.01]) plt.pyplot.show()
def plot(*args, **kwargs): ''' An abridged version of plt.plot().''' ax = plt.gca() return ax.plot(*args, **kwargs)
# pairs = np.zeros([len(seqDB),2]) #xToPlot= 'pearsonCorrToMTT' #yToPlot = 'pearsonCorrToMeanReplicate' xToPlot= 'spearmanCorrToMeanReplicate' yToPlot = 'pearsonCorrToMeanReplicate' for rowId in range(len(seqDB)): pairs[rowId,0] = seqDB.loc[rowId,xToPlot] #seqDB['num_cells'] ###X AXIS pairs[rowId,1] = seqDB.loc[rowId,yToPlot] ####Y AXIS plt.scatter(pairs[:,0],pairs[:,1]) plt.xlabel(xToPlot) plt.ylabel(yToPlot) axes = plt.gca() axes.set_xlim([0.8,1.05]) axes.set_ylim([0.8,1.05]) fig = plt.gcf() fig.set_size_inches(15,10) # In[12]: seqDB # In[21]: pairs = np.zeros([len(seqDB),2])
#xacl,yacl,zacl = force(container) #container.xacl = xacl #container.yacl = yacl #container.zacl = zacl integrator = Verlet(dt) setNeighbors = Neighbors() setNeighbors.UpdateNeighbors(container, cutOff) if animate == True: circles = [] fig = plt.figure(figsize = (10,8)) ax = plt.gca() ax.set_aspect('equal') ax.set_xlim((0,container.Lx)) ax.set_ylim((0,container.Ly)) ax.plot([0,10/sqrt(3)],[20,10],'b-') ax.plot([17/sqrt(3),27/sqrt(3)],[10,20],'b-') def prettify_circle(e): color="lightsteelblue" facecolor="green" alpha=.6 e.set_clip_box(ax.bbox) e.set_edgecolor( color ) e.set_linewidth(3) e.set_facecolor( facecolor ) # "none" not None e.set_alpha( alpha )
for array in fsr_kinf_error: nparray = numpy.array(array) fig = plt.figure() plt.pcolor( numpy.linspace(0, 5, 5), numpy.linspace(0, 5, 5), nparray, edgecolors="k", linewidths=1, vmin=nparray[:, :].min(), vmax=nparray[:, :].max(), ) plt.colorbar() plt.axis([0, 5, 0, 5]) plt.title("FSR K-infinity Errors") plt.gca().axes.get_xaxis().set_ticks([]) plt.gca().axes.get_yaxis().set_ticks([]) plt.show() fig.savefig(assembly_list[fsr_kinf_error.index(array)] + "-fsr-kinf-errors.jpeg") for array in fsr_mean_error: nparray = numpy.array(array) fig = plt.figure() plt.pcolor( numpy.linspace(0, 5, 5), numpy.linspace(0, 5, 5), nparray, edgecolors="k", linewidths=1, vmin=nparray[:, :].min(), vmax=nparray[:, :].max(),