def RugerApprTest(syn_data, A_inv, Biso_inv, Bani_inv, Az0_inv, ind_test, ang_list, az_list): f = plt.figure(facecolor= 'white', figsize = [14,7]) ax_an = f.add_subplot(121) PlotRugerAmp(ax_an, syn_data[ind_test].reshape( (1, len(az_list), len(ang_list) ), order = 'F'), 0, ang_list, az_list, cmap = cm.Accent, vid = 'An') ax_az = f.add_subplot(122) PlotRugerAmp(ax_az, syn_data[ind_test].reshape( (1, len(az_list), len(ang_list) ), order = 'F'), 0, ang_list, az_list, cmap = cm.Accent, vid = 'Az') f.tight_layout() for line in ax_an.lines: line.set_linewidth(0) for line in ax_az.lines: line.set_linewidth(0) cm_subsection = np.linspace(0.0, 1.0, len(az_list)) colors = [ cm.Accent(x) for x in cm_subsection ] for iaz, az in enumerate(az_list): amp_appr = A_inv[ind_test] + (Biso_inv[ind_test] + Bani_inv[ind_test]*sin(pi*(az - Az0_inv[ind_test])/180)**2)*sin(pi*ang_list/180)**2 ax_an.plot(ang_list, amp_appr, c = colors[iaz]) cm_subsection = np.linspace(0.0, 1.0, len(ang_list)) colors = [ cm.Accent(x) for x in cm_subsection ] for ian, an in enumerate(ang_list): amp_appr = A_inv[ind_test] + (Biso_inv[ind_test] + Bani_inv[ind_test]*sin(pi*(az_list - Az0_inv[ind_test])/180)**2)*sin(pi*an/180)**2 ax_az.plot(az_list, amp_appr, c = colors[ian])
def visualize_2D_gmm(points, w, mu, stdev, model_id, c, export=False): ''' plots points and their corresponding gmm model in 2D Input: points: N X 2, sampled points w: n_gaussians, gmm weights mu: 2 X n_gaussians, gmm means stdev: 2 X n_gaussians, gmm standard deviation (assuming diagonal covariance matrix) Output: None ''' n_gaussians = mu.shape[1] N = int(np.round(points.shape[0] / n_gaussians)) # Visualize data axes = plt.gca() colors = cmx.Accent(np.linspace( 0, 1, n_gaussians)) if id == 'human' else cmx.Paired( np.linspace(0, 1, n_gaussians)) for i in range(n_gaussians): idx = range(i * N, (i + 1) * N) for j in range(4): axes.add_patch( patches.Ellipse(mu[:, i], width=(j + 1) * stdev[0, i], height=(j + 1) * stdev[1, i], alpha=0.4, fill=True, color=colors[i])) plt.xlabel('Dim 1') plt.ylabel('Dim 2')
def plot_CCCs(CCCs, labels=None): if labels is None: labels = np.arange(len(CCCs)) colors = cm.Accent(np.linspace(0, 1, len(CCCs) + 1)) plt.figure(figsize=(10, 5)) ax = plt.gca() for (i, CC) in enumerate(CCCs): with CC.output().open() as f: res = dill.load(f) handle = sns.tsplot(res['sd_matrix'], ci='sd', color=colors[i], ax=ax, legend=False, time=res['training_set_sizes']) j = 0 for i in range(len(CCCs), 2 * len(CCCs)): handle.get_children()[i].set_label('{}'.format(labels[j])) j += 1 plt.semilogx() plt.axhline(0.5, linestyle='-', color='b', label='_nolegend_') plt.xlabel('num samples') plt.ylabel('Correctness Rate') plt.legend(loc=(0, 1.1))
def barplot(ax, hasildata): conditions = [(c, np.mean(hasildata[hasildata[:, 0] == c][:, 2].astype(float))) for c in np.unique(hasildata[:, 0])] categories = [(c, np.mean(hasildata[hasildata[:, 1] == c][:, 2].astype(float))) for c in np.unique(hasildata[:, 1])] conditions = [c[0] for c in sorted(conditions, key=o.itemgetter(1))] categories = [c[0] for c in sorted(categories, key=o.itemgetter(1))] space = 0.3 n = len(conditions) width = (1 - space) / (len(conditions)) # Create a set of bars at each position for i, cond in enumerate(conditions): indeces = range(1, len(categories) + 1) vals = hasildata[hasildata[:, 0] == cond][:, 2].astype(np.float) pos = [j - (1 - space) / 2. + i * width for j in indeces] ax.bar(pos, vals, width=width, label=cond, color=cm.Accent(float(i) / n)) # Set the x-axis tick labels to be equal to the categories ax.set_title('Perbandingan Jumlah Dosen seluruh fakultas yang mengakses Share.its.ac.id tahun 2016 - 2018') ax.set_xticks(indeces) ax.set_xticklabels(categories) plt.setp(plt.xticks()[1], rotation=90) # Add the axis labels ax.set_ylabel("Jumlah Dosen") ax.set_xlabel("Tahun") # Add a legend handles, labels = ax.get_legend_handles_labels() ax.legend(handles[::-1], labels[::-1], loc='upper left')
def barplot(ax, dpoints, ptitle=""): """ Function modified from Peter Kerpedjiev. http://emptypipes.org/2013/11/09/matplotlib-multicategory-barchart/ Create a barchart for data across different categories with multiple conditions for each category. Parameters ---------- ax: The plotting axes from matplotlib. dpoints: The data set as an (n, 3) numpy array ptitle: String title for plot """ # Aggregate the conditions and the categories according to their # mean values conditions = [(c, np.mean(dpoints[dpoints[:, 0] == c][:, 2].astype(float))) for c in np.unique(dpoints[:, 0])] categories = [(c, np.mean(dpoints[dpoints[:, 1] == c][:, 2].astype(float))) for c in np.unique(dpoints[:, 1])] # sort the conditions, categories and data so that the bars in # the plot will be ordered by category and condition conditions = [c[0] for c in sorted(conditions, key=o.itemgetter(1))] categories = [c[0] for c in sorted(categories, key=o.itemgetter(1))] dpoints = np.array(sorted(dpoints, key=lambda x: categories.index(x[1]))) # the space between each set of bars space = 0.3 n = len(conditions) width = (1 - space) / (len(conditions)) # Create a set of bars at each position for i, cond in enumerate(conditions): indeces = range(len(categories)) #indeces = range(1, len(categories)+1) vals = dpoints[dpoints[:, 0] == cond][:, 2].astype(np.float) pos = [j - (1 - space) / 2. + i * width for j in indeces] ax.bar(pos, vals, width=width, label=cond, color=cm.Accent(float(i) / n)) # Set the x-axis tick labels to be equal to the categories ax.set_xticks(indeces) ax.set_xticklabels(categories) plt.setp(plt.xticks()[1], rotation=50) # Add the axis labels ax.set_ylabel("energy (kcal/mol)") ax.set_title(ptitle) # Add a legend handles, labels = ax.get_legend_handles_labels() ax.legend(handles[::-1], labels[::-1], loc='upper left')
def barplot(self, ax, dpoints): ''' Create a barchart for data across different categories with multiple conditions for each category. @param ax: The plotting axes from matplotlib. @param dpoints: The data set as an (n, 3) numpy array ''' # Aggregate the conditions and the categories according to their # mean values conditions = [(c, np.mean(dpoints[dpoints[:, 0] == c][:, 2].astype(float))) for c in np.unique(dpoints[:, 0])] categories = [(c, np.mean(dpoints[dpoints[:, 1] == c][:, 2].astype(float))) for c in np.unique(dpoints[:, 1])] # sort the conditions, categories and data so that the bars in # the plot will be ordered by category and condition conditions = [c[0] for c in sorted(conditions, key=o.itemgetter(0))] categories = [c[0] for c in categories] dpoints = np.array( sorted(dpoints, key=lambda x: categories.index(x[1]))) # the space between each set of bars space = 0.3 n = len(conditions) width = (1 - space) / (len(conditions)) # Create a set of bars at each position for i, cond in enumerate(conditions): indeces = range(1, len(categories) + 1) vals = dpoints[dpoints[:, 0] == cond][:, 2].astype(np.float) pos = [j - (1 - space) / 2. + i * width for j in indeces] ax.bar(pos, vals, width=width, label=cond, color=cm.Accent(float(i) / n)) # Set the x-axis tick labels to be equal to the categories ax.set_xticks(indeces) ax.set_xticklabels(categories) plt.setp(plt.xticks()[1], rotation=90) # Add the axis labels ax.set_ylabel("Ratios") ax.set_xlabel("Marker Genes") # Add a legend handles, labels = ax.get_legend_handles_labels() ax.legend(handles[::-1], labels[::-1], loc='upper left', bbox_to_anchor=(-0.4, 0.6))
def barplot(ax, dpoints): ''' Create a barchart for data across different categories with multiple conditions for each category. @param ax: The plotting axes from matplotlib. @param dpoints: The data set as an (n, 3) numpy array ''' # Aggregate the conditions and the categories according to their # mean values conditions = [(c, np.mean(dpoints[dpoints[:,0] == c][:,2].astype(float))) for c in np.unique(dpoints[:,0])] categories = [(c, np.mean(dpoints[dpoints[:,1] == c][:,2].astype(float))) for c in np.unique(dpoints[:,1])] # sort the conditions, categories and data so that the bars in # the plot will be ordered by category and condition conditions = [c[0] for c in sorted(conditions, key=o.itemgetter(1))] print conditions # categories = [c[0] for c in sorted(categories, key=o.itemgetter(1))] # print conditions # print categories conditions=['CPU','UPFRONT','CPU_OPREP','UPFRONT_OPREP','CPU_OPREP_COLLABORATOR','UPFRONT_OPREP_COLLABORATOR'] categories=['5.0','6.0','7.0','8.0','9.0'] # print conditions # print categories dpoints = np.array(sorted(dpoints, key=lambda x: categories.index(x[1]))) print dpoints # the space between each set of bars space = 0.3 n = len(conditions) width = (1 - space) / (len(conditions)) # Create a set of bars at each position for i,cond in enumerate(conditions): indeces = range(1, len(categories)+1) vals = dpoints[dpoints[:,0] == cond][:,2].astype(np.float) stds = dpoints[dpoints[:,0] == cond][:,3].astype(np.float) pos = [j - (1 - space) / 2. + i * width for j in indeces] ax.bar(pos, vals, width=width, label=cond,yerr=stds,ecolor='k',color=cm.Accent(float(i) / n)) # Set the x-axis tick labels to be equal to the categories ax.set_xticks(indeces) ax.set_xticklabels(categories) plt.setp(plt.xticks()[1], rotation=90) # Add the axis labels ax.set_ylabel("RMSD") ax.set_xlabel("Structure") # Add a legend handles, labels = ax.get_legend_handles_labels() ax.legend(loc="lower left")
def plot(df, k, title): # see: http://emptypipes.org/2013/11/09/matplotlib-multicategory-barchart/ fig = plt.figure() ax = fig.add_subplot(111) space = 0.3 df = rename_columns(rename_indexes(df)) conditions = df.index.values # ie. combinations categories = df.columns.values # ie. decades n = len(conditions) width = (1 - space) / (len(conditions)) for i, combination in enumerate(conditions): indeces = range(1, len(categories) + 1) vals = df.ix[combination].tolist() pos = [ j - (1 - space) / 2. + i * width for j in range(1, len(categories) + 1) ] rects = ax.bar(pos, vals, width=width, label=combination, color=cm.Accent(float(i) / n)) if (k > 3): continue # skip the % labeling with k is too big for rect in rects: height = rect.get_height() ax.text(rect.get_x() + rect.get_width() / 2., 1.08 * height, '{0:.2f}%'.format(height * 100), ha='center', va='bottom', rotation=90) ax.set_ylabel("% of occurrence") ax.set_title(title) ax.set_xticks(indeces) ax.set_xticklabels(categories) ax.yaxis.set_major_formatter(FuncFormatter(to_percent)) ax.set_ylim((ax.get_ylim()[0], ax.get_ylim()[1] * 1.25)) box = ax.get_position( ) # Shrink current axis's height by 10% on the bottom ax.set_position( [box.x0, box.y0 + box.height * 0.1, box.width, box.height * 0.9]) ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05), fancybox=True, shadow=True, ncol=5) # Put a legend below current axis plt.show(block=False)
def barplot(ax, dpoints): ''' Create a barchart for data across different genres with multiple users for each genre. @param ax: The plotting axes from matplotlib. @param dpoints: The data set as an (n, 3) numpy array ''' # Aggregate the users and the genres according to their # mean values users = [(user, np.mean(dpoints[dpoints[:,0] == user][:,2].astype(float))) for user in np.unique(dpoints[:,0])] genres = [(genre, np.mean(dpoints[dpoints[:,1] == genre][:,2].astype(float))) for genre in np.unique(dpoints[:,1])] # sort the users, genres and data so that the bars in # the plot will be ordered by genre and user users = [user[0] for user in sorted(users, key=op.itemgetter(1))] genres = [genre[0] for genre in sorted(genres, key=op.itemgetter(1))] dpoints = np.array(sorted(dpoints, key=lambda x: genres.index(x[1]))) # print(dpoints) # the space between each set of bars space = 0.3 n = len(users) width = (1 - space) / (len(users)) # Create a set of bars at each position for i,user in enumerate(users): indeces = range(1, len(genres)+1) vals = dpoints[dpoints[:,0] == user][:,2].astype(np.float) pos = [j - (1 - space) / 2. + i * width for j in indeces] ax.bar(pos, vals, width=width, label=user, color=cm.Accent(float(i) / n)) # Set the x-axis tick labels to be equal to the genres ax.set_xticks(indeces) ax.set_xticklabels(genres) plt.setp(plt.xticks()[1], rotation=90) # Add the axis labels ax.set_ylabel("Movies (%)") ax.set_xlabel("Genres") # Add a legend handles, labels = ax.get_legend_handles_labels() ax.legend(handles[::-1], labels[::-1], loc='upper left') #barplot(ax, dpoints) #savefig('barchart_3.png') #plt.show()
def plot_clusters(self): self.cluster_data = [] for clstr_file in glob.iglob(self.file_patt): f_name = os.path.basename(clstr_file) perc = f_name.split('.cd_hits.clstr')[0].split('_')[-1] clstr_len = len(filter(lambda line : line.startswith('>C'),\ open(clstr_file).read().splitlines())) self.cluster_data.append([f_name.rsplit('_',2)[0], int(float(perc)*100),#remove trailing zeros clstr_len]) if not self.cluster_data: raise Exception, "No cd_hit '*.cd_hits.clstr' files found" dpoints = np.array(self.cluster_data) fig = plt.figure() ax = fig.add_subplot(111) space = 0.3 conditions = [(c, np.mean(dpoints[dpoints[:,0] == c][:,2].astype(float))) for c in np.unique(dpoints[:,0])] categories = [(c, np.mean(dpoints[dpoints[:,1] == c][:,2].astype(float))) for c in np.unique(dpoints[:,1])] conditions = [c[0] for c in sorted(conditions, key=o.itemgetter(1))] pprint.pprint(conditions) categories = [c[0] for c in sorted(categories, key=o.itemgetter(1))] pprint.pprint(categories) dpoints = np.array(sorted(dpoints, key=lambda x: categories.index(x[1]))) print(dpoints) np.savetxt("CDhit_counts.tsv", dpoints, fmt ="%s %s %s") n = len(conditions) width = (1 - space)/(len(conditions)) for i,cond in enumerate(conditions): indices = range(1, len(categories)+1) vals = dpoints[dpoints[:,0] == cond][:,2].astype(np.float) pos = [j - (1 - space) / 2. + i * width for j in range(1,len(categories)+1) ] ax.bar(pos, vals, width=width, label=cond, color=cm.Accent(float(i) / n - i/n)) ax.set_xticks(indices) ax.set_xticklabels(categories) plt.setp(plt.xticks()[1], rotation=0) plt.rc('legend',**{'fontsize':8}) font = { 'fontname':'sans-serif', 'weight': 'bold', 'size': 14} ax.set_ylabel("Number of CD-HIT clusters", fontdict=font) ax.set_xlabel("Clustering sequence identity (%)", fontdict=font) handles, labels = ax.get_legend_handles_labels() ax.legend(handles[::-1], labels[::-1], loc='upper left') plt.savefig(os.path.join(self.working_dir, '.'.join(['CDhit_counts', self.plot_type])))
def plot_annotation_class_quantification(self, plot_path): all_classes_sorted = set() no_of_libs = len(self._lib_names) for directions in self._lib_names_and_class_quanti.values(): for classes_and_counting in directions.values(): for anno_class in classes_and_counting.keys(): all_classes_sorted.add(anno_class) all_classes_sorted = sorted(list(all_classes_sorted)) bottom = np.array([0] * no_of_libs) fig = plt.figure() ax = plt.subplot(111) font = {'family': 'sans-serif', 'weight': 'normal', 'size': 6} matplotlib.rc('font', **font) plt.title("Number of reads per RNA classes") color_index = 0 for direction in self._lib_names_and_class_quanti[ self._lib_names[0]].keys(): for anno_class in all_classes_sorted: countings = [ self._lib_names_and_class_quanti[lib][direction] [anno_class] for lib in self._lib_names ] color = cm.Accent(1.0 / (float(len(all_classes_sorted)) * 2) * color_index) plt.bar(range(no_of_libs), countings, align="center", bottom=bottom, linewidth=0, color=color, width=0.5, label=anno_class + " " + direction) bottom = bottom + countings color_index += 1 plt.xticks(np.array(range(no_of_libs)), self._lib_names, rotation=45, ha="right") plt.tight_layout() ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['left'].set_visible(False) ax.xaxis.set_ticks_position("none") plt.legend(loc="upper right", frameon=False, ncol=4) fig.savefig(plot_path)
def barplot(ax, dpoints): ''' Create a barchart for data across different categories with multiple conditions for each category. @param ax: The plotting axes from matplotlib. @param dpoints: The data set as an (n, 4) numpy array ''' # Aggregation conditions = [(c, np.mean(dpoints[dpoints[:,0] == c][:,2].astype(float))) for c in np.unique(dpoints[:,0])] categories = [(c, np.mean(dpoints[dpoints[:,1] == c][:,2].astype(float))) for c in np.unique(dpoints[:,1])] conditions = [c[0] for c in sorted(conditions, key=o.itemgetter(1))] categories = [c[0] for c in sorted(categories, key=o.itemgetter(1))] dpoints = np.array(sorted(dpoints, key=lambda x: categories.index(x[1]))) # Space between each set of bars space = 0.3 n = len(conditions) width = (1 - space) / (len(conditions)) # Set of Bars at each position for i,cond in enumerate(conditions): indices = range(1, len(categories)+1) vals = dpoints[dpoints[:,0] == cond][:,2].astype(np.float) pos = [j - (1 - space) / 2. + i * width for j in indices] ax.bar(pos, vals, width=width, label=cond, color=cm.Accent(float(i) / n)) # x-axis tick labels= Regression Model O/P ax.set_xticks(indices) ax.set_xticklabels(categories) plt.setp(plt.xticks()[1], rotation=90) # Axis labels ax.set_ylabel("Accuracy") ax.set_xlabel("Regression Models") # Legend handles, labels = ax.get_legend_handles_labels() ax.legend(handles[::-1], labels[::-1], loc='upper left')
def barplot(ax, dpoints): # Aggregate the conditions and the categories according to their # mean values conditions = [(c, np.mean(dpoints[dpoints[:, 0] == c][:, 2].astype(float))) for c in np.unique(dpoints[:, 0])] categories = [(c, np.mean(dpoints[dpoints[:, 1] == c][:, 2].astype(float))) for c in np.unique(dpoints[:, 1])] # sort the conditions, categories and data so that the bars in # the plot will be ordered by category and condition conditions = [c[0] for c in sorted(conditions, key=o.itemgetter(1))] categories = [c[0] for c in sorted(categories, key=o.itemgetter(1))] dpoints = np.array(sorted(dpoints, key=lambda x: categories.index(x[1]))) # the space between each set of bars space = 0.2 n = len(conditions) width = (1 - space) / (len(conditions)) # Create a set of bars at each position for i, cond in enumerate(conditions): indeces = range(1, len(categories) + 1) vals = dpoints[dpoints[:, 0] == cond][:, 2].astype(np.float) pos = [j - (1 - space) / 2. + i * width for j in indeces] ax.bar(pos, vals, width=width, label=cond, color=cm.Accent(float(i) / n)) # Set the x-axis tick labels to be equal to the categories ax.set_xticks(indeces) ax.set_xticklabels(categories) plt.setp(plt.xticks()[1], rotation=90) # Add the axis labels ax.set_ylabel("Tweets") ax.set_xlabel("Marcas") # Add a legend handles, labels = ax.get_legend_handles_labels() ax.legend(handles[::-1], labels[::-1], loc='upper left')
def apply_plot_attributes(var, clr_x): ''' Make the individual plot lines prettier here. If you want different effects for different variables, you can use if-statements along with the name of the variable (which is passed in as the "var" argument, a string). clr_x is a number between 0 and 1 to apply to a matplotlib colormap ''' # Something about setting these curve attributes seems to kill the # VisIt color cycler. So we do one better by replacing it with a # matplotlib color cycler! # Good ones to try include Accent, Dark2, Set1, Set2, Vega10, spectral... this_color = tuple(int(val * 255) for val in cm.Accent(clr_x)) CurveAtts = CurveAttributes() ### set the curve color CurveAtts.curveColorSource = CurveAtts.Custom # Cycle, Custom CurveAtts.curveColor = this_color # RGBalpha ### turn off/on legend and labels CurveAtts.showLegend = 1 # legend on/off CurveAtts.showLabels = 0 # in-plot labels on/off ### line properties CurveAtts.showLines = 1 # on/off CurveAtts.lineStyle = CurveAtts.SOLID # SOLID, DASH, DOT, DOTDASH CurveAtts.lineWidth = 2 ### point properties (plot data points along the line) CurveAtts.showPoints = 0 # on/off CurveAtts.symbol = CurveAtts.Point # Point, TriangleUp, TriangleDown, Square, Circle, Plus, X CurveAtts.pointSize = 5 CurveAtts.pointFillMode = CurveAtts.Static # Static, Dynamic CurveAtts.pointStride = 1 # plot every n data-points CurveAtts.symbolDensity = 50 ### fill below the plot line to the x-axis CurveAtts.fillMode = CurveAtts.NoFill # NoFill, Solid, HorizontalGradient, VerticalGradient CurveAtts.fillColor1 = (0, 255, 0, 255) CurveAtts.fillColor2 = (100, 255, 100, 255 ) # used to make a gradient effect SetPlotOptions(CurveAtts)
def tsne_plot_similar_words(title, labels, embedding_clusters, word_clusters, a, filename): plt.figure(figsize=(16, 9)) colors = cm.Accent(np.linspace(0, 1, len(labels))) for label, embeddings, words, color in zip(labels, embedding_clusters, word_clusters, colors): x = embeddings[:, 0] y = embeddings[:, 1] plt.scatter(x, y, c=color, alpha=a, label=label) for i, word in enumerate(words): plt.annotate(word, alpha=0.5, xy=(x[i], y[i]), xytext=(5, 2), textcoords='offset points', ha='center', va='bottom', size=17) plt.legend(loc=4, fontsize='xx-large') plt.title(title) plt.grid(True) if filename: plt.savefig(filename, format='png', dpi=150, bbox_inches='tight') plt.show()
def get_nice_colors(n_colors): ''' Not Original code: Generages list of n "nice" colors ''' return cm.Accent( [1 - (i/n_colors) for i in range(n_colors)] )
def call(self): '''Main work routine of the snuffling.''' all = [] for traces in self.chopper_selected_traces(fallback=True): for trace in traces: all.append(trace) extrema = [] colors = iter(cm.Accent(num.linspace(0., 1., len(all)))) if self.want_smoothing: alpha = 0.2 additional = 'and smoothing' else: alpha = 1. additional = '' minf = 0. maxf = 0. pblabel = 'Calculating amplitude spectra %s' % additional pb = self.get_viewer().parent().get_progressbars() pb.set_status(pblabel, 0) num_traces = len(all) maxval = float(num_traces) plot_data = [] plot_data_supplement = [] for i_tr, tr in enumerate(all): val = i_tr / maxval * 100. pb.set_status(pblabel, val) tr.ydata = tr.ydata.astype(num.float) tr.ydata -= tr.ydata.mean() f, a = tr.spectrum() minf = min([f.min(), minf]) maxf = max([f.max(), maxf]) absa = num.abs(a) labsa = num.log(absa) stdabsa = num.std(labsa) meanabsa = num.mean(labsa) mi, ma = meanabsa - 3 * stdabsa, meanabsa + 3 * stdabsa extrema.append(mi) extrema.append(ma) c = next(colors) plot_data.append((f, num.abs(a))) plot_data_supplement.append((c, alpha, '.'.join(tr.nslc_id))) if self.want_smoothing: smoothed = self.konnoohmachi(num.abs(a), f, self.b) plot_data.append((f, num.abs(smoothed))) plot_data_supplement.append((c, 1., '.'.join(tr.nslc_id))) self.get_viewer().update() pb.set_status(pblabel, 100.) fig = self.figure(name='Amplitude Spectra') p = fig.add_subplot(111) args = ('c', 'alpha', 'label') for d, s in zip(plot_data, plot_data_supplement): p.plot(*d, **dict(zip(args, s))) mi, ma = min(extrema), max(extrema) p.set_xscale('log') p.set_yscale('log') p.set_ylim(num.exp(mi), num.exp(ma)) p.set_xlim(minf, maxf) p.set_xlabel('Frequency [Hz]') p.set_ylabel('Counts') handles, labels = p.get_legend_handles_labels() leg_dict = dict(zip(labels, handles)) if num_traces > 1: p.legend(list(leg_dict.values()), list(leg_dict.keys()), loc=2, borderaxespad=0., bbox_to_anchor=((1.05, 1.))) fig.subplots_adjust(right=0.8, left=0.1) else: p.set_title(list(leg_dict.keys())[0], fontsize=16) fig.subplots_adjust(right=0.9, left=0.1) fig.canvas.draw()
def compute_distance_error(plot=False, plotIndividualTags=False): np.set_printoptions(suppress=True) # no scientific notation parser = argparse.ArgumentParser("Compute error of aruco estimate pose") parser.add_argument("detected_markers", help="The output of deter_markers_in_video") parser.add_argument("timestamps", help="The timestamps file for video stream") parser.add_argument("mocaprobotfile", help="The robot poses from vicon") parser.add_argument( "top_left_dot_poses", help="the hand-written csv file listing global positions top-left dots" ) parser.add_argument( "dot_offsets", help= "the hand-written csv file listing offsets of all points for each tag") args = parser.parse_args() # parse data from files aruco_data, timestamps = parse_aruco_data(args.detected_markers, args.timestamps) robot_pose = parse_bot_pose(args.mocaprobotfile) tag_poses = parse_tag_top_left(args.top_left_dot_poses) tag_offsets = parse_tag_points(args.dot_offsets) tag_centers = get_center_tag_poses_from_dots(tag_poses, tag_offsets) # apply time shift to account for delay in camera start-up aruco_data[:, 0] += 0.55 output = [] for i in range(aruco_data.shape[0]): temp = [] aruco_sample = aruco_data[i, :] tag_id = aruco_sample[1] timestamp = aruco_sample[0] corresponding_mocap_idx = (np.abs(robot_pose[:, 0] - timestamp)).argmin() robot_pose_temp = robot_pose[corresponding_mocap_idx, :] try: tag_pose = tag_centers[0][np.where( tag_centers[0][:, 12] == tag_id)[0][0], :-1] except Exception: continue mocap_robot_to_tag = robot_pose_temp[1:4] - np.array( [0, 0, .17]) - tag_pose[0:3] # timestamp (aruco), tag id, truth (mocap), measured (aruco) temp.append(timestamp) temp.append(tag_id) temp.append(np.linalg.norm(mocap_robot_to_tag)) temp.append(np.linalg.norm(aruco_sample[2:5])) temp.append( np.abs( np.linalg.norm(mocap_robot_to_tag) - np.linalg.norm(aruco_sample[2:5]))) # error temp.append(corresponding_mocap_idx) output.append(temp) output = np.array(output) mean_dist = np.mean(output[:, 4]) st_dev_dist = np.std(output[:, 4]) pct95 = np.percentile(output[:, 4], 95) pct5 = np.percentile(output[:, 4], 5) print("Mean error distance", mean_dist) print("St dev distance", st_dev_dist) print("pct95 error distance", pct95) print("pct5 dev distance", pct5) if plot: recorded_data_processing_dir = os.path.dirname( os.path.realpath(__file__)) style = recorded_data_processing_dir + "/../phil.mplstyle" plt.style.use(style) plt.figure() colors_vicon = cm.Accent(np.linspace(0, 1, tag_poses.shape[0])) colors_aruco = cm.Set1(np.linspace(0, 1, tag_poses.shape[0])) for i in range(tag_centers[0].shape[0]): try: mean_errors_idxs = np.where(output[:, 1] == tag_centers[0][i, 12])[0] except Exception as e: continue if (mean_errors_idxs.shape[0] > 0): errors_by_tag = [] temp = [] for err in mean_errors_idxs: errors_by_tag.append(output[err, 4]) temp.append(output[err, :]) temp = np.array(temp) labelV = "Vicon Tag " + str(int(tag_centers[0][i, 12])) labelA = "ArUco Tag " + str(int(tag_centers[0][i, 12])) idx = np.where(tag_poses[:, 0] == int(tag_centers[0][i, 12])) plt.scatter(temp[:, 0], temp[:, 2], s=10, color=colors_vicon[idx[0][0]], label=labelV) plt.scatter(temp[:, 0], temp[:, 3], s=10, color=colors_aruco[idx[0][0]], label=labelA) if plotIndividualTags: lgnd = plt.legend() plt.title( "Distance from Camera to Tag (ArUco vs Vicon) Trial 0") plt.ylabel("Distance (meters)") plt.xlabel("time (seconds)") plt.tick_params() mean_dist = np.mean(temp[:, 4]) st_dev_dist = np.std(temp[:, 4]) pct95 = np.percentile(temp[:, 4], 95) pct5 = np.percentile(temp[:, 4], 5) print("Mean error distance tag ", int(temp[0, 1]), "=", mean_dist) print("St dev distance tag ", int(temp[0, 1]), "=", st_dev_dist) print("pct95 error distance tag ", int(temp[0, 1]), "=", pct95) print("pct5 dev distance tag ", int(temp[0, 1]), "=", pct5) plt.show() # print(np.mean(errors_by_tag)) # print(tag_centers[0][i,12] ) # plot corresponding_mocap_idx over time # plt.scatter(output[:,0], output[:,5], s=10, color="g") lgnd = plt.legend() # for i in range(len(lgnd.legendHandles)): # lgnd.legendHandles[i]._sizes = [40] plt.title("Distance from Camera to Tag (ArUco vs Vicon) Trial 1") plt.ylabel("Distance (meters)") plt.xlabel("time (seconds)") plt.tick_params() plt.show()
def unsupervised_cmap(n): return ListedColormap([cm.Accent(i) for i in np.linspace(0, 1, n)])
def plot(data, title, xlabel, ylabel, filename=None): """ Plot error analysis statistics. In particular, plot a bar chart for the numbers described in ``data``. Args: data (list(str, list((str,int)))): The data to be plotted. The ith entry of this list contains the name which will appear in the legend, and a list of (category, count) pairs. These are the individual data points which will be plotted. title (str): Title of the plot. xlabel (str): Label of the x axis. ylabel (str): Label of the y axis. filename (str, optional): If set, write plot to ``filename``. Example:: pair_errs = errors["pair"]["recall_errors"]["all"] tree_errs = errors["tree"]["recall_errors"]["all"] plot( [("pair", [(cat, len(pair_errs[cat])) for cat in pair_errs.keys()]), ("tree", [(cat, len(tree_errs[cat])) for cat in tree_errs.keys()])], "Recall Errors", "Type of anaphor", "Number of Errors") """ rcParams['xtick.major.pad'] = '12' rcParams['ytick.major.pad'] = '12' fig, ax = pyplot.subplots() systems = [] categories = [] colors = cm.Accent(numpy.linspace(0, 1, len(data))) bars_for_legend = [] for i, system_data in enumerate(data): system_name, categories_and_numbers = system_data systems.append(system_name) for j, cat_and_number in enumerate(categories_and_numbers): category, number = cat_and_number if category not in categories: categories.append(category) bar = ax.bar(2 * j + i * (1 / len(data)), number, color=colors[i], width=1 / len(data), label=system_name) if j == 0: bars_for_legend.append(bar) xticks = [2 * k + 0.5 for k in range(0, len(categories))] pyplot.title(title, fontsize=28) pyplot.xlabel(xlabel, fontsize=24) pyplot.ylabel(ylabel, fontsize=24) ax.spines["top"].set_visible(False) ax.spines["right"].set_visible(False) ax.get_xaxis().tick_bottom() ax.get_yaxis().tick_left() ax.set_xticklabels(categories) ax.set_xticks(xticks) pyplot.tick_params(axis='both', which='major', labelsize=20) if filename: legend = ax.legend(bars_for_legend, systems, loc='upper right', bbox_to_anchor=(1.2, 1.2)) fig.savefig(filename, bbox_extra_artists=(legend, ), bbox_inches='tight') else: legend = ax.legend(bars_for_legend, systems, loc='upper right') legend.draggable() fig.show()
plt.rcParams['figure.facecolor'] = "white" plt.rcParams['svg.fonttype'] = 'none' plt.rcParams['pdf.fonttype'] = '42' contrib_ids = ["thermexp", "gic", "gis_smb", "gis_sid", "ant_smb", "ant_sid"] # Note: "gic" has specific plot script. plot_these = ["thermexp"] # ,"thermexp","gic","gis_smb","gis_sid"] for contrib in plot_these: calibdata = pickle.load( open("../data/calibration/" + contrib + ".pkl", "rb")) observations = cs.__dict__[contrib + "_observations"] cols = [ cm.Accent(np.float(k) / len(observations)) for k in np.arange(len(observations)) ] fig = plt.figure(5) plt.subplots_adjust(bottom=0.06, top=0.95) plt.clf() ax = plt.subplot(111) for i, obs in enumerate(observations): print obs params = calibdata["params"][obs] offset = i * 1. / 400. if contrib == "thermexp":
from datetime import datetime import networkx as nx import nxviz as nxv ##### from matplotlib import cm words = ['Biological Process', 'Molecular Function', 'Cellular Component'] pie_colors = { 'Set3': cm.Set3(np.arange(12) / 12.), 'Set2': cm.Set2(np.arange(8) / 8.), 'Set1': cm.Set1(np.arange(9) / 9.), 'Pastel2': cm.Pastel2(np.arange(8) / 8.), 'Pastel1': cm.Pastel1(np.arange(9) / 9.), 'Dark2': cm.Dark2(np.arange(8) / 8.), 'Paired': cm.Paired(np.arange(12) / 12.), 'Accent': cm.Accent(np.arange(8) / 8.), 'Spectral': cm.Spectral(np.arange(11) / 11.) } colors = { '#8DD3C7': pie_colors['Set3'][0:1], '#FFFFB3': pie_colors['Set3'][1:2], '#BEBADA': pie_colors['Set3'][2:3], '#FB8072': pie_colors['Set3'][3:4], '#80B1D3': pie_colors['Set3'][4:5], '#FDB462': pie_colors['Set3'][5:6], '#B3DE69': pie_colors['Set3'][6:7], '#FCCDE5': pie_colors['Set3'][7:8], '#D9D9D9': pie_colors['Set3'][8:9], '#BC80BD': pie_colors['Set3'][9:10], '#CCEBC5': pie_colors['Set3'][10:11], '#FFED6F': pie_colors['Set3'][11:12]
def makeHbarPlot(self, ax, dpoints, condition_colormap = None, xlabel = None, ylabel = None , axLabelSize = 22, tickLabelSize = 18, addLegend = False): ''' Create a barchart for data across different categories with multiple conditions for each category. @param self: The Object pointer @param ax: The plotting axes from matplotlib. @param dpoints: The data set as an (n, 3) numpy array (category, condition, value) ''' # Aggregate the conditions and the categories according to their # mean values conditions = [(c, np.mean(dpoints[dpoints[:,0] == c][:,2].astype(float))) for c in np.unique(dpoints[:,0])] for c in np.unique(dpoints[:,1]): print dpoints[dpoints[:,1] == c][0][1] if self.sortoption == 'mean': categories = [(c, np.mean(dpoints[dpoints[:,1] == c][:,2].astype(float))) for c in np.unique(dpoints[:,1])] elif self.sortoption == 'alphabetical': categories = [(c, dpoints[dpoints[:,1] == c][0][1]) for c in np.unique(dpoints[:,1])] print categories # sort the conditions, categories and data so that the bars in # the plot will be ordered by category and condition conditions = [c[0] for c in sorted(conditions, key=o.itemgetter(1))] categories = [c[0] for c in sorted(categories, key=o.itemgetter(1),reverse=True)] dpoints = np.array(sorted(dpoints, key=lambda x: categories.index(x[1]))) # the space between each set of bars n = len(conditions) width = (1 - self.space) / (len(conditions)) # Create a set of bars at each position for i,cond in enumerate(conditions): indeces = range(1, len(categories)+1) vals = dpoints[dpoints[:,0] == cond][:,2].astype(np.float) pos = [j - (1 - self.space) / 2. + i * width for j in indeces] # check if condition specific numbers present if not condition_colormap == None: barcolors = condition_colormap[cond] else: barcolors = cm.Accent(float(i) / n) ax.barh(pos, vals, height=width, label=cond, color= barcolors) ax.set_yticks(indeces) ax.set_yticklabels(categories, ha = 'left') ax.tick_params(axis='both', which='major', labelsize=tickLabelSize) ax.tick_params(axis='both', which='minor', labelsize=tickLabelSize) # Add the axis labels if not ylabel == None: ax.set_ylabel(ylabel) if not xlabel == None: ax.set_xlabel(xlabel, fontsize = 22) handles, labels = ax.get_legend_handles_labels() # Add a legend if addLegend: ax.legend(handles[::-1], labels[::-1], loc='upper center', bbox_to_anchor=(0.5, 1.11), ncol = 2, frameon=False) return handles, labels
silhouette_values = silhouette_samples(cdf, kmdff['prediction']) ax[mapping[i]].set_xticks([-0.15, 0.0, 0.25, 0.5, 0.75, 1.0]) ax[mapping[i]].set_yticks([]) ax[mapping[i]].set_title('%d clusters' % n) ax[mapping[i]].set_xlim([-0.15, 1]) y_lower = 20 for t in range(n): ct_values = silhouette_values[Y == t] ct_values.sort() y_upper = y_lower + ct_values.shape[0] color = cm.Accent(float(t) / n) ax[mapping[i]].fill_betweenx(np.arange(y_lower, y_upper), 0, ct_values, facecolor=color, edgecolor=color) y_lower = y_upper + 20 plt.show() # Compute the other metrics for K=2 km = KMeans(n_clusters=2, max_iter=1000, random_state=1000) Y_pred = km.fit_predict(cdf) df_km = pd.DataFrame(Y_pred, columns=['prediction'], index=cdf.index) kmdff = pd.concat([dff, df_km], axis=1)
def plot_pie(labels, fracs, figname): ###设置图布长宽比为8:6 fig = plt.figure(figsize=(8, 6), dpi=300) ###设置图形占整个画图的区域是111 ax5 = fig.add_subplot(111) ###从cm中选取颜色,否则默认颜色很丑 colors = cm.Accent(np.linspace(0, 1, len(labels))) ###圆里面的文本格式,%3.1f%%表示小数有三位,整数有一位的浮点数 autopct = '%1.1f%%' ###给每个labels加一个数字标识,以免有些labels太长,图例和图形上都不好展示 sign = range(1, len(labels) + 1) ###画图 startangle表示从第一块从哪个角度开始逆时针旋转,startangle=0表示第一块从90度开始逆时针旋转 patches, texts = ax5.pie(fracs, labels=sign, labeldistance=1.1, shadow=False, colors=colors, startangle=0) #for t in texts2: # t.set_size = 300 tmplabels = [] total = sum(fracs) a = 0 ###得到图例legend展示所需的labels即tmplabels for i in xrange(len(labels)): a += 1 lable = labels[i] size = float(fracs[i]) / total * 100 tmplabels.append(str(a) + ": " + lable + " %1.1f%%" % size) ###图例的绘制 ###bbox_to_anchor表示图例位置;fontsize表示图例大小;frameon表示图例最外框线 legend = ax5.legend( patches, tmplabels, bbox_to_anchor=(1.6, 1.1), borderaxespad=0, fontsize=7, frameon=True, shadow=True, fancybox=True, ) frame = legend.get_frame() frame.set_facecolor('0.90') #frame = legend.get_frame() #frame.set_alpha(1) #frame.set_facecolor('black') #frame.set_edgecolor('red') ###设置图形位置 pie = ax5.get_position() ###pie.width表示图形占宽从左边开始的0.7,这是为了更好的展示出图例,否则有时图例会与图形重合 ax5.set_position([pie.x0, pie.y0, pie.width * 0.7, pie.height]) ###设置图形中各个部分之前的线条宽度及颜色,白色会好看些,默认为黑色 for w in patches: w.set_linewidth(0.2) w.set_edgecolor('white') ###为了保持圆形为正规圆形,如果不设置,当figsize不成比例,图形大小也会改变 plt.axis('equal') plt.savefig(figname + ".png", format='png', dpi=300) plt.savefig(figname + ".svg", format='svg', dpi=300) plt.close(0) return (0)
pos = [ j - (1 - space) / 2. + i * width - .95 for j in range(1, 1 + len(placements)) ] else: if INCLUDE_COUZIN and SINGLE_ROW: pos = [ j - (1 - space) / 2. + i * width - 1.05 for j in range(1, 1 + len(placements)) ] if INCLUDE_STDDEV: ax1.bar(pos, gs1[:, i], width=width, label=local, color=cm.Accent(float(i) / n), yerr=gs1stddev[:, i]) if not SINGLE_ROW: ax2.bar(pos, gs2[:, i], width=width, label=local, color=cm.Accent(float(i) / n), yerr=gs2stddev[:, i]) ax3.bar(pos, gs3[:, i], width=width, label=local, color=cm.Accent(float(i) / n), yerr=gs3stddev[:, i]) if INCLUDE_EXTRAS:
def getColorFromMap(self, float_color): return cm.Accent(float_color)
def getColorFromMap(self, double_color): return cm.Accent(double_color)
def cmap(i): return cm.Accent(float(i) / (a_dim + x_dim))
def generate__colors(colorType="default", nColors=10, seaborn=True, howto=False): if (howto == True): print( "[generate__colors.py] generate__colors( colorType=, nColors=, seaborn=T/F, howto=T/F )" ) print( "[generate__colors.py] colorType = [ \ \n"\ "default, bright, deep, muted, colorblind, pastel, \n"\ "jet, tab10, tab20, hsv, accent, pastel1, pastel2, set1, set2, set3 \n"\ " ] ") return () # ------------------------------------------------- # # --- [1] generate colors --- # # ------------------------------------------------- # if (not (seaborn)): if (colorType.lower() == "jet"): colors = [cm.jet(ik / float(nColors)) for ik in range(nColors)] elif (colorType.lower() == "tab10"): colors = [cm.tab10(ik / float(nColors)) for ik in range(nColors)] elif (colorType.lower() == "tab20"): colors = [cm.tab20(ik / float(nColors)) for ik in range(nColors)] elif (colorType.lower() == "hsv"): colors = [cm.hsv(ik / float(nColors)) for ik in range(nColors)] elif (colorType.lower() == "accent"): colors = [cm.Accent(ik / float(nColors)) for ik in range(nColors)] elif (colorType.lower() == "pastel1"): colors = [cm.Pastel1(ik / float(nColors)) for ik in range(nColors)] elif (colorType.lower() == "pastel2"): colors = [cm.Pastel2(ik / float(nColors)) for ik in range(nColors)] elif (colorType.lower() == "set1"): colors = [cm.Set1(ik / float(nColors)) for ik in range(nColors)] elif (colorType.lower() == "set2"): colors = [cm.Set2(ik / float(nColors)) for ik in range(nColors)] elif (colorType.lower() == "set3"): colors = [cm.Set3(ik / float(nColors)) for ik in range(nColors)] else: print("[generate__colors.py] colorType == ?? ") sys.exit() else: if (colorType.lower() == "jet"): print("[generate__colors.py] no jet palette for seaborn") sys.exit() elif (colorType.lower() == "default"): colors = sns.color_palette(n_colors=nColors) elif (colorType.lower() == "deep"): colors = sns.color_palette(palette="deep", n_colors=nColors) elif (colorType.lower() == "colorblind"): colors = sns.color_palette(palette="colorblind", n_colors=nColors) elif (colorType.lower() == "dark"): colors = sns.color_palette(palette="dark", n_colors=nColors) elif (colorType.lower() == "bright"): colors = sns.color_palette(palette="bright", n_colors=nColors) elif (colorType.lower() == "muted"): colors = sns.color_palette(palette="muted", n_colors=nColors) elif (colorType.lower() == "pastel"): colors = sns.color_palette(palette="pastel", n_colors=nColors) elif (colorType.lower() == "hsv"): colors = sns.color_palette(palette="hsv", n_colors=nColors) elif (colorType.lower() == "accent"): colors = sns.color_palette(palette="Accent", n_colors=nColors) elif (colorType.lower() == "pastel1"): colors = sns.color_palette(palette="Pastel1", n_colors=nColors) elif (colorType.lower() == "pastel2"): colors = sns.color_palette(palette="Pastel2", n_colors=nColors) elif (colorType.lower() == "tab10"): colors = sns.color_palette(palette="tab10", n_colors=nColors) elif (colorType.lower() == "tab20"): colors = sns.color_palette(palette="tab20", n_colors=nColors) elif (colorType.lower() == "set1"): colors = sns.color_palette(palette="Set1", n_colors=nColors) elif (colorType.lower() == "set2"): colors = sns.color_palette(palette="Set2", n_colors=nColors) elif (colorType.lower() == "set3"): colors = sns.color_palette(palette="Set3", n_colors=nColors) else: colors = sns.color_palette(palette=colorType, n_colors=nColors) # ------------------------------------------------- # # --- [2] return --- # # ------------------------------------------------- # return (colors)