def _add_bgcolors(df, ax): # background for a, method in enumerate(df['method'].unique()): if a % 2: ax.axhspan(a - .5, a + .5, color='0.9', zorder=-1) if a <= 5: facecolor = cm.Set2(7) elif a > 6 and a < 9: facecolor = cm.Set2(3) elif a > 10: facecolor = cm.Set2(4) if method not in ['dummy1', 'dummy2']: ax.axhspan(a - .5, a + .5, facecolor=facecolor, alpha=0.15) return ax
def plot_cube(cube, name='voxel', angle=20, IMG_DIM=80, num_class=12): from mpl_toolkits.mplot3d import Axes3D # cube = normalize(cube) # Note that cm.Paired has 12 colors and Set2 has 8 colors # cube[np.where(cube > num_class)] = 10 if num_class == 12: cube[cube < 0] = 0 cube[cube == 255] = 0 facecolors = cm.Paired((np.round(cube) / 13)) facecolors[:, :, :, -1] = 0.2 * np.tanh( cube * 1000) + 0.7 * (cube > 5) + 0.1 * (cube == 2) elif num_class == 4: facecolors = cm.Dark2((np.round(cube) / 9)) facecolors[:, :, :, -1] = 0.4 * np.tanh(cube * 1000) elif num_class == 3: # cube[cube == -1] = 3 cube[cube < 0] = 0 facecolors = cm.Set2((np.round(cube) / 9)) facecolors[:, :, :, -1] = 0.03 * np.tanh(cube * 1000) + 0.6 * (cube == 1) elif num_class == 1: cube[cube < 0] = 0 facecolors = cm.Dark2((np.round(cube) / 1)) facecolors[:, :, :, -1] = 0.5 * (cube == 1) # make the alpha channel more similar to each others while 0 is still 0 facecolors = explode(facecolors) filled = facecolors[:, :, :, -1] != 0 x, y, z = expand_coordinates( np.indices(np.array(filled.shape) + 1).astype(float)) # Here is a loop for generating demo files for idx, val in enumerate(np.arange(160, 170, 10)): fig = plt.figure(figsize=(45 / 2.54, 45 / 2.54)) # , dpi=150) # plot ax1 = fig.add_subplot(111, projection='3d') # For samples in SUNCG, 20, -40 is a good choice for visualization # ax1.view_init(np.abs(90-val/2), val) ax1.view_init(angle, val) ax1.set_xlim(right=IMG_DIM * 2) ax1.set_ylim(top=IMG_DIM * 2) ax1.set_zlim(top=IMG_DIM * 2) ax1.set_axis_off() ax1.voxels(x, y, z, filled, facecolors=facecolors, edgecolors=np.clip(2 * facecolors - 0.5, 0, 1), linewidth=0.5) # plt.show() plt.savefig(name + '_' + format(idx, '03d') + '.png', bbox_inches='tight', pad_inches=0, transparent=True) plt.close(fig) """
def draw(folders): """ draw folder size for given folder""" figsize = (8, 8) # keep the figure square ldo, rup = 0.1, 0.8 # leftdown and right up normalized fig = plt.figure(figsize=figsize) ax = fig.add_axes([ldo, ldo, rup, rup], polar=True) # transform data x = [os.path.basename(x['path']) for x in folders] y = [y['size'] / 1024 / 1024 for y in folders] theta = np.arange(0, 2 * np.pi, 2 * np.pi / len(x)) radii = y bars = ax.bar(theta, radii) middle = 90 / len(x) theta_ticks = [t * (180 / np.pi) + middle for t in theta] lines, labels =plt.thetagrids(theta_ticks, labels=x, frac=0.5) for step, each in enumerate(labels): each.set_rotation(theta[step] * (180 / np.pi) + middle) each.set_fontsize(8) # configure bars colormap = lambda r:cm.Set2(r / len(x)) for r, each in zip(radii, bars): each.set_facecolor(colormap(r)) each.set_alpha(0.5) plt.show
def make_size_graphs(all_df_list, distances, param_name, outdir): # Matplotlib settings needed to create complex bar plots mpl.rcParams['font.size'] = 6 mpl.rcParams['figure.dpi'] = 250 scale_y = 1e3 bins = np.linspace(0, 150, 20) purity_list = [] for df in all_df_list: purity_list.append(df[param_name]) graphs_per_row = 4 num_rows = int(len(distances) / graphs_per_row + 1) fig = plt.figure( ) # plt.subplots(num_rows, graphs_per_row, constrained_layout = True) cmap = cm.Set2(np.linspace(0, 1, len(purity_list))) x = [] for i in range(num_rows): x += [i] * graphs_per_row y = list(range(graphs_per_row)) * num_rows for i, p in enumerate(purity_list): ax = plt.subplot2grid((num_rows, graphs_per_row), (x[i], y[i])) #, constrained_layout = True) ax.hist(p, bins, color=cmap[i]) # ax.plot(bins[:-1], hist_list[i], color = cmap[i]) ax.set_title(f'Search Distance = {distances[i]}') ax.set(xlabel=param_name, ylabel='Prop. Read Clouds') fig.tight_layout() fig.savefig('{}/{}.png'.format(outdir, param_name), format='png', dpi=1200)
def plot_elems_per_group(groups_count, filename, plot_mean=False): fig, ax = plt.subplots() rects1 = ax.bar(np.arange(len(groups_count)), groups_count, 0.5, color=cm.Set2(.3)) ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.tick_params(color='gray', bottom=False, labelbottom=False, grid_alpha=0.5) if plot_mean: mean = np.mean(groups_count) plt.axhline(y=np.mean(groups_count), color='red', linestyle='--', linewidth=2) ax.text(len(groups_count) - 1.5, mean + 10, 'Mean: %s' % (mean.round(2)), size=15, color='red') plt.ylabel('Items in the group') plt.xlabel('Groups') fig.savefig(filename) plt.close(fig) return plt
def model_dictionary(): models = ['ACCESS1-0', 'ACCESS1-3', 'BNU-ESM','CCSM4', 'CESM1-BGC',\ 'CESM1-CAM5', 'CESM1-FASTCHEM', 'CESM1-WACCM', 'CMCC-CESM',\ 'CMCC-CM','CMCC-CMS', 'CNRM-CM5', 'CNRM-CM5','CNRM-CM5-2', 'CSIRO-Mk3-6-0', 'CanESM2',\ 'FGOALS-g2', 'FGOALS-s2', 'FIO-ESM', 'GFDL-CM3', 'GFDL-ESM2G',\ 'GFDL-ESM2M', 'GFDL-HIRAM-C180','GFDL-HIRAM-C360','GISS-E2-H*p1', 'GISS-E2-H*p3', 'GISS-E2-H-CC',\ 'GISS-E2-R*p1', 'GISS-E2-R*p3', 'GISS-E2-R-CC', 'HadCM3',\ 'HadGEM2-AO', 'HadGEM2-CC', 'HadGEM2-ES', 'IPSL-CM5A-LR',\ 'IPSL-CM5A-MR', 'IPSL-CM5B-LR', 'MIROC-ESM', 'MIROC-ESM-CHEM',\ 'MIROC4h', 'MIROC5', 'MPI-ESM-LR', 'MPI-ESM-MR', 'MPI-ESM-P','MRI-CGCM3',\ 'NorESM1-M', 'NorESM1-ME', 'bcc-csm1-1', 'bcc-csm1-1-m', 'fio-esm',\ 'inmcm4'] markers =["o","v","^","<",">","8","s","p","*","h","H","D","d"]#,"P","X"] Lm = len(markers) d={} i=0 colors = [cm.Set1(i/9.) for i in range(9)]+[cm.Set2(i/9.) for i in range(9)]+[cm.Set3(i/9.) for i in range(9)] Lc = len(colors) for i in range(len(models)): model =models[i] d[model]= {} d[model]["color"]=colors[np.mod(i,Lc)] d[model]["marker"]=markers[np.mod(i,Lm)] d["Can*"]=d["CanESM2"] d["CanAM4"]=d["CanESM2"] d["HadGEM2-A*"]=d["HadGEM2-AO"] d["HadGEM2-A"]=d["HadGEM2-AO"] return d
def draw_buffer(self): self.buff_win = pg.GraphicsLayoutWidget() self.buff_win.setWindowTitle('Buffer Status') self.buff_win.resize(800, 700) self.total_peers = self.number_of_monitors + self.number_of_peers + self.number_of_malicious self.p4 = self.buff_win.addPlot() self.p4.showGrid( x=True, y=True, alpha=100) # To show grid lines across x axis and y axis leftaxis = self.p4.getAxis('left') # get left axis i.e y axis leftaxis.setTickSpacing( 5, 1) # to set ticks at a interval of 5 and grid lines at 1 space # Get different colors using matplotlib library if self.total_peers < 8: colors = cm.Set2(np.linspace(0, 1, 8)) elif self.total_peers < 12: colors = cm.Set3(np.linspace(0, 1, 12)) else: colors = cm.rainbow(np.linspace(0, 1, self.total_peers + 1)) self.QColors = [ pg.hsvColor(color[0], color[1], color[2], color[3]) for color in colors ] # Create QtColors, each color would represent a peer self.Data = [ ] # To represent buffer out i.e outgoing data from buffer self.OutData = [] # To represent buffer in i.e incoming data in buffer # a single line would reperesent a single color or peer, hence we would not need to pass a list of brushes self.lineIN = [None] * self.total_peers for ix in range(self.total_peers): self.lineIN[ix] = self.p4.plot(pen=(None), symbolBrush=self.QColors[ix], name='IN', symbol='o', clear=False) self.Data.append(set()) self.OutData.append(set()) # similiarly one line per peer to represent outgoinf data from buffer self.lineOUT = self.p4.plot(pen=(None), symbolBrush=mkColor('#CCCCCC'), name='OUT', symbol='o', clear=False) self.p4.setRange(xRange=[0, self.total_peers], yRange=[0, self.get_buffer_size()]) self.buff_win.show() # To actually show create window self.buffer_order = {} self.buffer_index = 0 self.buffer_labels = [] self.lastUpdate = pg.ptime.time() self.avgFps = 0.0
def test_paga_pie(image_comparer, pbmc): save_and_compare_images = image_comparer(ROOT, FIGS, tol=30) colors = { c: {cm.Set1(_): 0.33 for _ in range(3)} for c in pbmc.obs["bulk_labels"].cat.categories } colors["Dendritic"] = {cm.Set2(_): 0.25 for _ in range(4)} sc.pl.paga(pbmc, color=colors, colorbar=False) save_and_compare_images('master_paga_pie')
def save_dorder_plots(img, K_comps=7, cmap='hsv'): fun = { 'hsv': lambda t: cm.hsv(colors.Normalize(vmin=0, vmax=K_comps) (t), bytes=True), 'Set1': lambda t: cm.Set1(colors.Normalize(vmin=0, vmax=K_comps)(t), bytes=True), 'Set2': lambda t: cm.Set2(colors.Normalize(vmin=0, vmax=K_comps)(t), bytes=True) } return fun[cmap](K_comps - img)
def make_main_graphs(all_df_list, distances, param_name, outdir): # Matplotlib settings needed to create complex bar plots mpl.rcParams['font.size'] = 6 mpl.rcParams['figure.dpi'] = 250 scale_y = 1e3 bins = np.linspace(0, 1, 20) purity_list = [] hist_list = [] for df in all_df_list: curr_lst = df[param_name] purity_list.append(curr_lst) curr_hist, bins = np.histogram(curr_lst, bins=bins) curr_freqs = np.divide(curr_hist, len(curr_lst)) hist_list.append(curr_freqs) fig = plt.figure() cmap = cm.Set2(np.linspace(0, 1, len(all_df_list))) plt.hist(purity_list, bins, label=distances, color=cmap) plt.legend(prop={'size': 6}, title='Search\nDistance') plt.xlabel(param_name) plt.ylabel('Num. Read Clouds') fig.savefig('{}/{}.png'.format(outdir, param_name), format='png', dpi=1200) plt.clf() graphs_per_row = 4 num_rows = int(len(distances) / graphs_per_row + 1) fig = plt.figure( ) # plt.subplots(num_rows, graphs_per_row, constrained_layout = True) x = [] for i in range(num_rows): x += [i] * graphs_per_row y = list(range(graphs_per_row)) * num_rows for i in range(len(hist_list)): ax = plt.subplot2grid((num_rows, graphs_per_row), (x[i], y[i])) #, constrained_layout = True) ax.plot(bins[:-1], hist_list[i], color=cmap[i]) ax.set_title(f'Search Distance = {distances[i]}') ax.set(xlabel=param_name, ylabel='Prop. Read Clouds') # axs[x[i],y[i]].plot(bins[:-1], hist_list[i], color = cmap[i]) # axs[x[i],y[i]].set_title(f'Search Distance = {distances[i]}') # for ax in axs.flat: # ax.set(xlabel='Purity', ylabel='Prop. Read Clouds') # Hide x labels and tick labels for everything but the left- and right-most plots. Removed because different axis scales. # for ax in axs.flat: # ax.label_outer() fig.tight_layout() fig.savefig('{}/{}_scaled.png'.format(outdir, param_name), format='png', dpi=1200)
def test_paga(image_comparer): # Sometimes things shift a pixel or so, resulting in diffs up to ~27 # The 1px-edges aren’t that good actually as they’re ignored at this tol … save_and_compare_images = image_comparer(ROOT, FIGS, tol=30) pbmc = sc.datasets.pbmc68k_reduced() sc.tl.paga(pbmc, groups='bulk_labels') common = dict(threshold=0.5, max_edge_width=1.0, random_state=0, show=False) # delete bulk_labels_colors to test the creation of color list by paga del pbmc.uns['bulk_labels_colors'] sc.pl.paga(pbmc, **common) save_and_compare_images('master_paga') sc.pl.paga(pbmc, color='CST3', **common) save_and_compare_images('master_paga_continuous') pbmc.obs['cool_feature'] = pbmc[:, 'CST3'].X.squeeze() sc.pl.paga(pbmc, color='cool_feature', **common) save_and_compare_images('master_paga_continuous_obs') sc.pl.paga(pbmc, color=['CST3', 'GATA2'], **common) save_and_compare_images('master_paga_continuous_multiple') sc.pl.paga_compare(pbmc, legend_fontoutline=2, **common) save_and_compare_images('master_paga_compare') sc.pl.paga_compare(pbmc, color='CST3', legend_fontsize=5, **common) save_and_compare_images('master_paga_compare_continuous') sc.pl.paga_compare(pbmc, basis='X_pca', legend_fontweight='normal', **common) save_and_compare_images('master_paga_compare_pca') colors = { c: {cm.Set1(_): 0.33 for _ in range(3)} for c in pbmc.obs["bulk_labels"].cat.categories } colors["Dendritic"] = {cm.Set2(_): 0.25 for _ in range(4)} sc.pl.paga(pbmc, color=colors, colorbar=False) save_and_compare_images('master_paga_pie')
def _create_categorical_colors(n_categories: int): if n_categories > 51: raise ValueError( f"Maximum number of colors (51) exceeded: `{n_categories}`.") colors = [cm.Set1(i) for i in range(cm.Set1.N)][:n_categories] colors += [cm.Set2(i) for i in range(cm.Set2.N)][:n_categories - len(colors)] colors += [cm.Set3(i) for i in range(cm.Set3.N)][:n_categories - len(colors)] colors += [cm.tab10(i) for i in range(cm.tab10.N)][:n_categories - len(colors)] colors += [cm.Paired(i) for i in range(cm.Paired.N)][:n_categories - len(colors)] return _convert_to_hex_colors(colors)
def plot_points(data, clustered_class): plt.figure(figsize=[25, 12]) legend = list() classes = np.unique(clustered_class) colors = cm.Set2(np.linspace(0, 1, len(classes))) for i in range(len(classes)): cluster_data = data[np.where(clustered_class[:] == classes[i])] legend.append( plt.scatter(cluster_data[:, 0], cluster_data[:, 1], c=colors[i], s=10, alpha=0.9)) plt.legend(legend, classes.astype(int)) plt.title("Hierarchical - Min") plt.show()
def plot_multi_obj_opt_multi_plot(smiles, target_mol, idx=0): with open('all_molecules_with_id.json') as f: molid = json.load(f) colors = iter(cm.rainbow(np.linspace(0, 1, 6))) colors = iter(cm.Set2(np.linspace(0, 1, 8))) colors = sns.color_palette('husl', 6) colors = ['#eae471', '#c1e092', '#83b49d', '#448fad', '#3e60c3', '#5a26a6'] smiles = tidy_smiles(smiles) # plt.figure() all_sim = [] all_qed = [] target_sim, target_qed = get_properties(target_mol, target_mol) for i in range(6): ssl = smiles['weight_%i' % i] sim, qed = zip( *[get_properties(ss, target_molecule=target_mol) for ss in ssl]) all_sim += list(sim) all_qed += list(qed) fig, ax = plt.subplots(nrows=3, ncols=2, sharex=True, sharey=True) i = 0 for row in ax: for col in row: ssl = smiles['weight_%i' % i] sim, qed = zip( * [get_properties(ss, target_molecule=target_mol) for ss in ssl]) # col.scatter(all_sim, all_qed, color='#d4d4d4') col.scatter(sim, qed, label='w=%.1f' % (i * 0.2), color=colors[i]) col.axvline(x=target_sim, ls='dashed', color='grey') col.axhline(y=target_qed, ls='dashed', color='grey') leg = col.legend(loc='lower left', handletextpad=0.0) leg.get_frame().set_alpha(0.75) col.set_ylim((-0.2, 1)) col.set_xlim((-0.1, 1.1)) i += 1 fig.text(0.5, 0.02, 'Similarity', ha='center') fig.text(0.02, 0.5, 'QED', va='center', rotation='vertical') fig.text(0.5, 0.94, molid[target_mol], ha='center') plt.subplots_adjust(left=0.10, bottom=0.14, right=0.96, top=0.92, wspace=0.12) plt.savefig('batch/mult_obj_gen_{}.pdf'.format(idx))
def make_secondary_graphs(param_list, distances, param_name, outdir): # param_stdev # Matplotlib settings needed to create complex bar plots mpl.rcParams['font.size'] = 6 mpl.rcParams['figure.dpi'] = 250 scale_y = 1e3 fig = plt.figure() cmap = cm.Set2(np.linspace(0, 1, len(param_list))) # y_error = [np.subtract(param_list, param_stdev), np.add(param_list, param_stdev)] plt.bar(distances, param_list, color=cmap) # yerr = y_error, plt.xlabel('Search Distance') plt.ylabel(param_name) param2strng = param_name.replace(' ', '_').replace('.', '') fig.savefig('{}/{}.png'.format(outdir, param2strng), format='png', dpi=1200)
def make_status_graphs(param_df, distances, param_name, outdir): # param_stdev # Matplotlib settings needed to create complex bar plots mpl.rcParams['font.size'] = 6 mpl.rcParams['figure.dpi'] = 250 scale_y = 1e3 # fig = plt.figure() cmap = cm.Set2(np.linspace(0, 1, param_df.shape[1])) ax = param_df.plot(kind='bar', color=cmap) fig = ax.get_figure() # y_error = [np.subtract(param_list, param_stdev), np.add(param_list, param_stdev)] # plt.bar(distances, param_df, color = cmap) # yerr = y_error, ax.set_xlabel('Search Distance') ax.set_ylabel(param_name) param2strng = param_name.replace(' ', '_').replace('.', '') fig.savefig('{}/{}.png'.format(outdir, param2strng), format='png', dpi=1200)
def plot_state_firing(emission_firing, x_in=4, y_in=5): """ """ N, M = emission_firing.shape # number of states, ncells fontsize_main, fontsize, linewidth_main, linewidth, markersize_main, markersize = figure_layout(x_in, 2.5) fig, ax = plt.subplots(1, N, figsize=(x_in, y_in)) colours = cm.Set2(np.linspace(0, 1, 8))[1:1+N] #cm.Set2(np.linspace(0, 1, N)) y_pos = np.arange(M)[1:] max_spks = np.round(np.max(emission_firing[:, 1:]), -1) for i_state, colour in enumerate(colours): #plt.subplot(1, N, i_state+1) ax[i_state].barh(y_pos, emission_firing[i_state, 1:], color=colour) if i_state == 0: ax[i_state].set_yticks(y_pos) else: ax[i_state].set_yticks([]) ax[i_state].set_xlim([0,max_spks]) ax[i_state].tick_params(labelsize=fontsize_main) return fig, ax
def make_paint_out_img(img, canny, verify=False): _, _, contours, _ = cv2.connectedComponentsWithStats(canny) contours = sorted([c for c in contours if c[4] > con_size_th], key=lambda x: -x[4]) if not contours: return # 最外殻(ページ画像そのもの)を取り出しておく orig = contours.pop(0) orig_width, orig_height = orig[2], orig[3] # 最外殻以外で大きすぎるものを除外 contours = [ c for c in contours if not (c[2] > orig_width * 0.9 and c[3] > orig_height * 0.9) ] if not contours: return for idx, con in enumerate(contours): x, y, w, h, size = con if verify: if idx < 8: color = cm.Set1(idx % 8) elif idx < 16: color = cm.Set2(idx % 8) else: color = cm.Set3(idx % 8) color = [int(c * 255) for c in color[:3]] else: color = (192, 192, 192) # GAのカラー画像、棺担ぎのクロが抜けるようになった img_p = cv2.rectangle(img, (x, y), (x + w, y + h), color, -1) if verify: img_p[veryfy_pix * idx:veryfy_pix * idx + veryfy_pix, :veryfy_pix] = color return img_p
def draw(self): # 绘制各文件夹的尺寸 fig = plt.figure(figsize=(8, 8)) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True) x = [os.path.basename(x['path']) for x in self.folders] y = [y['size']/1024/1024 for y in self.folders] theta = np.arange(0.0, 2*np.pi, 2 * np.pi / len(x)) radii = y bars = ax.bar(theta, radii) middle = 90 / len(x) theta_ticks = [t*(180/np.pi) + middle for t in theta] lines, labels = plt.thetagrids(theta_ticks, labels=x) for step, each in enumerate(labels): each.set_rotation(theta[step] * (180 /np.pi) + middle) each.set_fontsize(8) colormap = lambda r: cm.Set2(r/len(x)) for r, each in zip(radii, bars): each.set_facecolor(colormap(r)) each.set_alpha(0.5) plt.show()
""" 绘制极线图 在极坐标系统中,点被描述为半径距离(通常表示为r)和角度(通常表示为theta)。 角度可以用户弧度或者角度表示,但是matplotlib使用角度 使用polar()函数绘制极线图。polor()函数接收两个相同长度的参数theta和r。 函数也接收其他和plot()函数相同的格式化参数。 使用matplotlib.pyplot.rgrids()来切换半径网格的显示或者设置标签 使用matplotlib.pyplot.thetagrid()来配置角度刻度与标签 """ import numpy as np import matplotlib.cm as cm import matplotlib.pyplot as plt figsize = 7 colormap = lambda r: cm.Set2(r / 20.0) N = 18 # number of bars fig = plt.figure(figsize=(figsize, figsize)) """创建正方形图表,并向其添加极限坐标轴""" ax = fig.add_axes([0.2, 0.2, 0.7, 0.7], polar=True) theta = np.arange(0, 2 * np.pi, 2 * np.pi / N) radii = 20 * np.random.rand(N) width = np.pi / 4 * np.random.rand(N) bars = ax.bar(theta, radii, width=width, bottom=0) for r, bar in zip(radii, bars): bar.set_facecolor(colormap(r)) bar.set_alpha(0.6) plt.show()
def main(): # set up command line argument parser parser = argparse.ArgumentParser(description='Characterize fasta files by \ base composition and sequence length distribution') group = parser.add_argument_group('required arguments:') group.add_argument('-fa', '--fasta_files', required=True, nargs='+', help='one or more fasta files to characterize') group = parser.add_argument_group('optional arguments') group.add_argument( '-fd', '--fasta_descriptors', nargs='+', help='The descriptors to use for each fasta file. (If you provide any \ descriptors, you must provide as many descriptors as files. If you \ provide none, it will use the original fasta filename.)') group.add_argument( '-od', '--output_directory', default=".", help='output directory for filtered fastq files (default is current \ directory)') group.add_argument( '-op', '--output_prefix', default='characterize', help='output prefix for fasta plots (default is "characterize")') # print help if no arguments provided if len(sys.argv) <= 1: parser.print_help() sys.exit() # parse command line arguments args = parser.parse_args() # Pre-defined variables, constants, and settings input_file_format = 'fasta' ngroups = len(args.fasta_files) color_scheme = cm.Set2(np.arange(ngroups) / float(ngroups)) #color_scheme = ['r', 'b', 'lightcoral', 'lightskyblue'] base_comp_ymax = 0.4 base_comp_title = 'Base Composition' base_comp_ylabel = '' base_comp_xlabel = '' length_col_header = 'length' fasta_col_header = 'fasta' seq_len_title = 'Insert Length Distribution' seq_len_ylabel = '' seq_len_xlabel = 'insert length' max_plot_col = 4 seq_xmin, seq_xmax = [-100, 1200] output_prefix_base_comp = time.strftime("%Y%m%d") + "_" + \ args.output_prefix + "_base_comp" output_prefix_seq_len = time.strftime("%Y%m%d") + "_" + \ args.output_prefix + "_seq_lengths" resolution = 200 file_format = 'png' sns.set_style('white') # set output directory: output_dir = args.output_directory.strip('/') if not os.path.isdir(output_dir): print("Error: invalid output directory selection. Exiting...") sys.exit() # initialize necessary data structures base_comp_dict = {} seq_len_dict = {} # Get the fasta names fasta_names = [] for i in range(len(args.fasta_files)): fasta_file = args.fasta_files[i] if args.fasta_descriptors: fasta_name = args.fasta_descriptors[i] else: fasta_name = os.path.splitext(os.path.basename(fasta_file))[0] fasta_names.append(fasta_name) # gather information from fastas extract_data_from_fastas(args.fasta_files, fasta_names, input_file_format, base_comp_dict, seq_len_dict) # Plot results: plot_base_compositions(base_comp_dict, fasta_names, color_scheme, base_comp_title, base_comp_xlabel, base_comp_ylabel, base_comp_ymax, output_dir, output_prefix_base_comp, resolution, file_format) if len(fasta_names) < max_plot_col: seq_len_col_num = len(fasta_names) else: seq_len_col_num = max_plot_col plot_seq_distributions(seq_len_dict, fasta_names, length_col_header, fasta_col_header, seq_len_col_num, color_scheme, seq_len_title, seq_len_xlabel, seq_len_ylabel, seq_xmin, seq_xmax, output_dir, output_prefix_seq_len, resolution, file_format)
def add_graph(self, adjacency_matrix, node_coords, node_color='auto', node_size=50, edge_cmap=cm.bwr, edge_vmin=None, edge_vmax=None, edge_threshold=None, edge_kwargs=None, node_kwargs=None): """Plot undirected graph on each of the axes Parameters ---------- adjacency_matrix: numpy array of shape (n, n) represents the edges strengths of the graph. Assumed to be a symmetric matrix. node_coords: numpy array_like of shape (n, 3) 3d coordinates of the graph nodes in world space. node_color: color or sequence of colors color(s) of the nodes. node_size: scalar or array_like size(s) of the nodes in points^2. edge_cmap: colormap colormap used for representing the strength of the edges. edge_vmin: float, optional, default: None edge_vmax: float, optional, default: None If not None, either or both of these values will be used to as the minimum and maximum values to color edges. If None are supplied the maximum absolute value within the given threshold will be used as minimum (multiplied by -1) and maximum coloring levels. edge_threshold: str or number If it is a number only the edges with a value greater than edge_threshold will be shown. If it is a string it must finish with a percent sign, e.g. "25.3%", and only the edges with a abs(value) above the given percentile will be shown. edge_kwargs: dict will be passed as kwargs for each edge matlotlib Line2D. node_kwargs: dict will be passed as kwargs to the plt.scatter call that plots all the nodes in one go. """ # set defaults if edge_kwargs is None: edge_kwargs = {} if node_kwargs is None: node_kwargs = {} if node_color == 'auto': nb_nodes = len(node_coords) node_color = mpl_cm.Set2(np.linspace(0, 1, nb_nodes)) node_coords = np.asarray(node_coords) # decompress input matrix if sparse if sparse.issparse(adjacency_matrix): adjacency_matrix = adjacency_matrix.toarray() # make the lines below well-behaved adjacency_matrix = np.nan_to_num(adjacency_matrix) # safety checks if 's' in node_kwargs: raise ValueError("Please use 'node_size' and not 'node_kwargs' " "to specify node sizes") if 'c' in node_kwargs: raise ValueError("Please use 'node_color' and not 'node_kwargs' " "to specify node colors") adjacency_matrix_shape = adjacency_matrix.shape if (len(adjacency_matrix_shape) != 2 or adjacency_matrix_shape[0] != adjacency_matrix_shape[1]): raise ValueError( "'adjacency_matrix' is supposed to have shape (n, n)." ' Its shape was {0}'.format(adjacency_matrix_shape)) node_coords_shape = node_coords.shape if len(node_coords_shape) != 2 or node_coords_shape[1] != 3: message = ( "Invalid shape for 'node_coords'. You passed an " "'adjacency_matrix' of shape {0} therefore " "'node_coords' should be a array with shape ({0[0]}, 3) " 'while its shape was {1}').format(adjacency_matrix_shape, node_coords_shape) raise ValueError(message) if node_coords_shape[0] != adjacency_matrix_shape[0]: raise ValueError( "Shape mismatch between 'adjacency_matrix' " "and 'node_coords'" "'adjacency_matrix' shape is {0}, 'node_coords' shape is {1}". format(adjacency_matrix_shape, node_coords_shape)) if not np.allclose(adjacency_matrix, adjacency_matrix.T, rtol=1e-3): raise ValueError("'adjacency_matrix' should be symmetric") # For a masked array, masked values are replaced with zeros if hasattr(adjacency_matrix, 'mask'): if not (adjacency_matrix.mask == adjacency_matrix.mask.T).all(): raise ValueError( "'adjacency_matrix' was masked with a non symmetric mask") adjacency_matrix = adjacency_matrix.filled(0) if edge_threshold is not None: if isinstance(edge_threshold, _basestring): message = ("If 'edge_threshold' is given as a string it " 'should be a number followed by the percent sign, ' 'e.g. "25.3%"') if not edge_threshold.endswith('%'): raise ValueError(message) try: percentile = float(edge_threshold[:-1]) except ValueError as exc: exc.args += (message, ) raise # Keep a percentile of edges with the highest absolute # values, so only need to look at the covariance # coefficients below the diagonal lower_diagonal_indices = np.tril_indices_from(adjacency_matrix, k=-1) lower_diagonal_values = adjacency_matrix[ lower_diagonal_indices] edge_threshold = stats.scoreatpercentile( np.abs(lower_diagonal_values), percentile) elif not isinstance(edge_threshold, numbers.Real): raise TypeError('edge_threshold should be either a number ' 'or a string finishing with a percent sign') adjacency_matrix = adjacency_matrix.copy() threshold_mask = np.abs(adjacency_matrix) < edge_threshold adjacency_matrix[threshold_mask] = 0 lower_triangular_adjacency_matrix = np.tril(adjacency_matrix, k=-1) non_zero_indices = lower_triangular_adjacency_matrix.nonzero() line_coords = [ node_coords[list(index)] for index in zip(*non_zero_indices) ] adjacency_matrix_values = adjacency_matrix[non_zero_indices] for ax in self.axes.values(): ax._add_markers(node_coords, node_color, node_size, **node_kwargs) if line_coords: ax._add_lines(line_coords, adjacency_matrix_values, edge_cmap, vmin=edge_vmin, vmax=edge_vmax, **edge_kwargs) plt.draw_if_interactive()
def plot_top10_barchart( year, df, values, year_var, color_var, names_var, title='', label='', ax=None, **kwargs, ): """ Plots a barchart of the top 10 values colored by group. :param year: year to be plotted (int) :param df: dataset (pandas DataFrame) :param values: sorting variable name (string) :param year_var: year variable name (string) :param color_var: color group variable name (string) :param names_var: bar labels variable name (string) :param title: title (string) :param label: label and unit of the values (string) :param ax: graph axes Gif example of this graph: .. raw:: html <img src="example_top10.gif" height="620px" width="100%"> """ if not isinstance(year, int): raise TypeError(f"year must be an int, not {type(year)}") if not isinstance(df, pd.core.frame.DataFrame): raise TypeError(f"data must be a DataFrame not {type(df)}.") if len(df.shape) != 2: raise ValueError(f"data must be a matrix but shape is {df.shape}") for var in [values, year_var, color_var, names_var]: if var not in df.columns: raise ValueError(f"{var} is not a valid column name.") if not isinstance(title, str): raise TypeError(f"title must be a string not {type(title)}.") if not isinstance(label, str): raise TypeError(f"label must be a string not {type(label)}.") for var in [values, year_var]: if df[var].dtype not in [ 'int16', 'int32', 'int64', 'float16', 'float32', 'float64', ]: raise ValueError(f"{var} must contain numeric values") if df[df[year_var] == year].shape[0] == 0: raise ValueError("404 year not found in dataframe") if len(df[color_var].unique()) > 25: warnings.warn(f"Having too many groups will result in repeated colors") dff = (df[df[year_var] == year].sort_values(by=values, ascending=True).tail(10)) if ax is None: ax = plt.gca() ax.clear() ll = list(dict.fromkeys(df[color_var])) if len(ll) < 8: colors = dict(zip(ll, [cm.Set2(x) for x in linspace(0, 0.87, len(ll))])) else: colors = dict( zip( ll, [cm.Set2(x) for x in linspace(0, 0.87, 8)] + [cm.Set3(x) for x in linspace(0.09, 1, len(ll) - 8)], )) bars = ax.barh( dff[names_var], dff[values], color=[colors[x] for x in dff[color_var]], alpha=0.73, edgecolor='#998D8F', linewidth=1.5, **kwargs, ) dx = dff[values].max() / 200 for i, (value, name) in enumerate(zip(dff[values], dff[names_var])): if len(name) > 0.43 * value / dx: name = name[:int(0.43 * value / dx)] + '..' ax.text(value - dx, i, name, size=16, ha='right', va='center') ax.text(value + dx, i, f'{value:,.0f}', size=14, ha='left', va='center') ax.text( 0.97, 0.4, year, transform=ax.transAxes, color='#FFECEF', size=46, ha='right', weight=800, path_effects=[ path_effects.Stroke(linewidth=3, foreground='black'), path_effects.Normal(), ], ) ax.text(0, 1.06, label, transform=ax.transAxes, size=12, color='#777777') ax.xaxis.set_major_formatter(ticker.StrMethodFormatter('{x:,.0f}')) ax.xaxis.set_ticks_position('top') ax.tick_params(axis='x', colors='#777777', labelsize=12) ax.set_yticks([]) ax.margins(0, 0.01) ax.grid(which='major', axis='x', linestyle='-') ax.set_axisbelow(True) ax.text(0, 1.1, title, transform=ax.transAxes, size=22, weight=600, ha='left') plt.box(False) color_var_uniq = list(dict.fromkeys(dff[color_var][::-1])) lgd = ax.legend(bars, color_var_uniq, loc=(0.82, 0.03)) for i, j in enumerate(lgd.legendHandles): j.set_color([colors[x] for x in color_var_uniq][i])
def __init__(self, subj_dir, img): ''' Initialize the electrode picker with the user-defined MRI and co-registered CT scan in [subj_dir]. Images will be displayed using orientation information obtained from the image header. Images will be resampled to dimensions [256,256,256] for display. We will also listen for keyboard and mouse events so the user can interact with each of the subplot panels (zoom/pan) and add/remove electrodes with a keystroke. ''' QtCore.pyqtRemoveInputHook() self.subj_dir = subj_dir self.img = nib.load(img) # Get affine transform self.affine = self.img.affine self.fsVox2RAS = np.array([[-1., 0., 0., 128.], [0., 0., 1., -128.], [0., -1., 0., 128.], [0., 0., 0., 1.]]) # Apply orientation to the MRI so that the order of the dimensions will be # sagittal, coronal, axial self.codes = nib.orientations.axcodes2ornt( nib.orientations.aff2axcodes(self.affine)) img_data = nib.orientations.apply_orientation(self.img.get_data(), self.codes) self.voxel_sizes = nib.affines.voxel_sizes(self.affine) nx, ny, nz = np.array(img_data.shape, dtype='float') self.inv_affine = np.linalg.inv(self.affine) self.img_clim = np.percentile(img_data, (1., 99.)) self.img_data = img_data self.elec_data = np.nan + np.zeros((img_data.shape)) self.bin_mat = '' # binary mask for electrodes self.device_num = 0 # Start with device 0, increment when we add a new electrode name type self.device_name = '' self.devices = [ ] # This will be a list of the devices (grids, strips, depths) self.elec_num = dict() self.elecmatrix = dict() # This will be the electrode coordinates self.legend_handles = [] # This will hold legend entries self.elec_added = False # Whether we're in an electrode added state self.imsz = [256, 256, 256] self.current_slice = np.array( [self.imsz[0] / 2, self.imsz[1] / 2, self.imsz[2] / 2], dtype=np.float) self.fig = plt.figure(figsize=(12, 10)) self.fig.canvas.set_window_title('Electrode Picker') thismanager = plt.get_current_fig_manager() thismanager.window.setWindowIcon( QtGui.QIcon((os.path.join('icons', 'leftbrain_blackbg.png')))) self.im = [] self.elec_im = [] self.pial_im = [] self.cursor = [] self.cursor2 = [] im_ranges = [[0, self.imsz[1], 0, self.imsz[2]], [0, self.imsz[0], 0, self.imsz[2]], [0, self.imsz[0], 0, self.imsz[1]]] im_labels = [['Inferior', 'Posterior'], ['Inferior', 'Left'], ['Posterior', 'Left']] self.ax = [] self.contour = [False, False, False] self.pial_surf_on = True # Whether pial surface is visible or not self.T1_on = True # Whether T1 is visible or not # This is the current slice for indexing (as integers so python doesnt complain) cs = np.round(self.current_slice).astype(np.int) # Plot sagittal, coronal, and axial views for i in np.arange(3): self.ax.append(self.fig.add_subplot(2, 2, i + 1)) self.ax[i].set_axis_bgcolor('k') if i == 0: imdata = img_data[cs[0], :, :].T ctdat = ct_data[cs[0], :, :].T edat = self.elec_data[cs[0], :, :].T pdat = self.pial_data[cs[0], :, :].T elif i == 1: imdata = img_data[:, cs[1], :].T ctdat = ct_data[:, cs[1], :].T edat = self.elec_data[:, cs[1], :].T pdat = self.pial_data[:, cs[1], :].T elif i == 2: imdata = img_data[:, :, cs[2]].T ctdat = ct_data[:, :, cs[2]].T edat = self.elec_data[:, :, cs[2]].T pdat = self.pial_data[:, :, cs[2]].T # Show the MRI data in grayscale self.im.append(plt.imshow(imdata, cmap=cm.gray, aspect='auto')) # Overlay the CT on top in "hot" colormap, slightly transparent self.ct_im.append( plt.imshow(ctdat, cmap=cm.hot, aspect='auto', alpha=0.5, vmin=1000, vmax=3000)) # Overlay the electrodes image on top (starts as NaNs, is eventually filled in) self.elec_colors = mcolors.LinearSegmentedColormap.from_list( 'elec_colors', np.vstack( (cm.Set1(np.linspace(0., 1, 9)), cm.Set2(np.linspace(0., 1, 8))))) self.elec_im.append( plt.imshow(edat, cmap=self.elec_colors, aspect='auto', alpha=1, vmin=0, vmax=17)) # Overlay the pial surface self.pial_im.append(self.ax[i].contour(pdat, linewidths=0.5, colors='y')) self.contour[i] = True # Plot a green cursor self.cursor.append( plt.plot([cs[1], cs[1]], [ self.ax[i].get_ylim()[0] + 1, self.ax[i].get_ylim()[1] - 1 ], color=[0, 1, 0])) self.cursor2.append( plt.plot([ self.ax[i].get_xlim()[0] + 1, self.ax[i].get_xlim()[1] - 1 ], [cs[2], cs[2]], color=[0, 1, 0])) # Flip the y axis so brains are the correct side up plt.gca().invert_yaxis() # Get rid of tick labels self.ax[i].set_xticks([]) self.ax[i].set_yticks([]) # Label the axes self.ax[i].set_xlabel(im_labels[i][0]) self.ax[i].set_ylabel(im_labels[i][1]) self.ax[i].axis(im_ranges[i]) # Plot the maximum intensity projection self.ct_slice = 's' # Show sagittal MIP to start self.ax.append(self.fig.add_subplot(2, 2, 4)) self.ax[3].set_axis_bgcolor('k') self.im.append( plt.imshow(np.nanmax(ct_data[cs[0] - 15:cs[0] + 15, :, :], axis=0).T, cmap=cm.gray, aspect='auto')) self.cursor.append( plt.plot( [cs[1], cs[1]], [self.ax[3].get_ylim()[0] + 1, self.ax[3].get_ylim()[1] - 1], color=[0, 1, 0])) self.cursor2.append( plt.plot( [self.ax[3].get_xlim()[0] + 1, self.ax[3].get_xlim()[1] - 1], [cs[2], cs[2]], color=[0, 1, 0])) self.ax[3].set_xticks([]) self.ax[3].set_yticks([]) plt.gca().invert_yaxis() self.ax[3].axis([0, self.imsz[1], 0, self.imsz[2]]) self.elec_im.append( plt.imshow(self.elec_data[cs[0], :, :].T, cmap=self.elec_colors, aspect='auto', alpha=1, vmin=0, vmax=17)) plt.gcf().suptitle( "Press 'n' to enter device name in console, press 'e' to add an electrode at crosshair, press 'h' for more options", fontsize=14) plt.tight_layout() plt.subplots_adjust(top=0.9) cid2 = self.fig.canvas.mpl_connect('scroll_event', self.on_scroll) cid3 = self.fig.canvas.mpl_connect('button_press_event', self.on_click) cid = self.fig.canvas.mpl_connect('key_press_event', self.on_key) #cid4 = self.fig.canvas.mpl_connect('key_release_event', self.on_key) plt.show() self.fig.canvas.draw()
def plot_2d(x, xaxis, rmse, r): # _____________ Make plot _____________ fig = plt.figure(figsize=(7.2,4.5)) fig.subplots_adjust(hspace=0.3) fig.subplots_adjust(wspace=0.2) plt.rcParams['text.usetex'] = False plt.rcParams['font.family'] = "sans-serif" plt.rcParams['font.serif'] = "Helvetica" plt.rcParams['axes.linewidth'] = 1.5 plt.rcParams['axes.labelsize'] = 14 plt.rcParams['font.size'] = 14 plt.rcParams['legend.fontsize'] = 12 plt.rcParams['xtick.labelsize'] = 12 plt.rcParams['ytick.labelsize'] = 14 almost_black = '#262626' # change the tick colors also to the almost black plt.rcParams['ytick.color'] = almost_black plt.rcParams['xtick.color'] = almost_black # change the text colors also to the almost black plt.rcParams['text.color'] = almost_black # Change the default axis colors from black to a slightly lighter black, # and a little thinner (0.5 instead of 1) plt.rcParams['axes.edgecolor'] = almost_black plt.rcParams['axes.labelcolor'] = almost_black # set the box type of sequence number props = dict(boxstyle="round", facecolor='white', alpha=0.0, ec='white') # choose colormap colors = cm.Set2(np.arange(0,4)) ax2 = fig.add_subplot(111) #ax2 = fig.add_subplot(212) # ax1.plot(x, r[0,:], c=colors[0], lw=1.5, ls="-", label="$θ_{top 25cm}$", alpha=1.) # ax1.plot(x, r[1,:], c=colors[1], lw=1.5, ls="-", label="$θ_{all}$", alpha=1.) # ax1.plot(x, r[2,:], c=colors[2], lw=1.5, ls="-", label="$E_{tr}$", alpha=1.) # ax1.plot(x, r[3,:], c=colors[3], lw=1.5, ls="-", label="$E_{s}$", alpha=1.) ax2.plot(x, rmse[1,:], c=colors[0], lw=1.5, ls="-", label="$θ_{all}$", alpha=1.) ax2.plot(x, rmse[0,:], c=colors[1], lw=1.5, ls="-", label="$θ_{top}$", alpha=1.) ax3 = ax2.twinx() ax3.plot(x, rmse[2,:], c=colors[2], lw=1.5, ls="-", label="$E_{tr}$", alpha=1.) ax3.plot(x, rmse[3,:], c=colors[3], lw=1.5, ls="-", label="$E_{s}$", alpha=1.) # ax1.set(xticks=x, xticklabels=xaxis) # ax1.axis('tight') # ax1.set_ylim(0.,1.) # ax1.axvline(x=1 , ls="--") # ax1.set_ylabel('r') # ax1.text(0.02, 0.95, '(a)', transform=ax1.transAxes, fontsize=14, verticalalignment='top', bbox=props) # ax1.legend() ax2.set(xticks=x, xticklabels=xaxis) ax2.axis('tight') ax2.set_ylim(0.,0.2) #ax2.set_xlim(day_start,day_end) ax2.axvline(x=1 , ls="--") ax2.set_ylabel('RMSE of $θ_{all}$, $θ_{top}$ (m$^{3}$ m$^{-3}$)') #ax2.text(0.02, 0.95, '(b)', transform=ax2.transAxes, fontsize=14, verticalalignment='top', bbox=props) ax2.legend(loc='upper center', frameon=False) ax3.set(xticks=x, xticklabels=xaxis) ax3.axis('tight') ax3.set_ylim(0.,1.) #ax2.set_xlim(day_start,day_end) #ax3.axvline(x=1 , ls="--") ax3.set_ylabel('RMSE of $E_{tr}$, $E_{s}$ (mm d$^{-1}$)') # ax3.text(0.02, 0.95, '(b)', transform=ax2.transAxes, fontsize=14, verticalalignment='top', bbox=props) ax3.legend(loc='upper right', frameon=False) fig.savefig("./plots/EucFACE_hyds-Opt" , bbox_inches='tight', pad_inches=0.1)
def plot_data_states(x, X, Z, state_prob, state_stable, logprob=-np.inf, tws=[-400, 400], x_in=4, y_in=5, separation=None, text=None): """ """ N = state_prob.shape[1] M = 1 #number of subplot fontsize_main, fontsize, linewidth_main, linewidth, markersize_main, markersize = figure_layout(x_in, 2.5)#y_in) #plt.figure(figsize=(20,8)) # for i_x, x_i in enumerate(X): # plt.subplot(M+1,1,i_x+1) # plt.plot(x, x_i, 'k') # plt.ylabel('#spikes', fontsize=fontsize) # #plt.ylabel('spikes cell; %d' % i_x) # plt.subplot(M+1,1,1) fig, ax1 = plt.subplots(figsize=(x_in, y_in))#(10,7) ax2 = ax1.twinx() colours = cm.Set2(np.linspace(0, 1, 8))[1:1+N] #cm.Set2(np.linspace(0, 1, N))#rainbow(np.linspace(0, 1, N)) #max_prob = np.max(state_prob, axis=1) max_prob = [] max_prob += [state_prob[i_z, z_i] for i_z, z_i in enumerate(Z)] max_prob = np.array(max_prob, dtype=np.float) for i_state, colour in enumerate(colours): #pos_i = Z==i_state #ax2.plot(x[state_stable[:,i_state]], np.zeros(state_stable[:,i_state].sum()), '|', markersize=20, color=colour)#*1.1 #commented 05/06 #ax2.plot(x[state_stable[:,i_state]], max_prob[state_stable[:,i_state]], 'ko', markersize=7) #ax2.plot(x[pos_i], np.ones(pos_i.sum())*1.1, 's', markersize=7, color=colour) ax2.plot(x, state_prob[:,i_state], '-', linewidth=linewidth_main, color=colour, alpha=0.7) #mport matplotlib.transforms as mtransforms #trans = mtransforms.blended_transform_factory(ax2.transData, ax2.transAxes) ax2.fill_between(x, 0, state_prob[:,i_state], where = state_stable[:,i_state], facecolor=colour, alpha=0.5) plt.xlim(tws) ax2.yaxis.tick_right() ax2.set_yticks([]) ax2.set_ylim([0,1.1]) ax2.tick_params(labelsize=fontsize_main) for i_cell, cell_i in enumerate(X): cell_i = np.reshape(cell_i, (np.size(cell_i),1)) cell_to_plot = cell_i[np.logical_and(cell_i>=tws[0], cell_i<tws[1])] digitize_event = np.digitize(cell_to_plot, x) -1 ax1.plot(x[digitize_event], np.repeat(i_cell+1, len(cell_to_plot)), '|k', markersize=markersize, alpha=1.0, zorder=10)#'dk', markersize=20) #'Xk', markersize=5 ax1.set_ylim([0,len(X)+1]) ax1.set_yticks(range(1,len(X)+1)) ax1.tick_params(labelsize=fontsize_main) #ax1.set_xlabel('Time [ms]', fontsize=fontsize_main) #ax1.set_ylabel('Neurons', fontsize=fontsize_main) #ax2.set_ylabel(r'$P(S_t|X_t)$', fontsize=fontsize_main) #ax2.ylim([0,1.1]) #fig.tight_layout() # max_prob = np.max(state_prob, axis=1) # #pos_max = np.argmax(state_prob, axis=1) # plt.subplot(M+1,1,M+1) # for i_state, state_i in enumerate(range(N)): # pos_i = Z==state_i # plt.plot(x[state_stable[:,i_state]], max_prob[state_stable[:,i_state]], 'ko', markersize=5) # plt.plot(x[pos_i], max_prob[pos_i], '.', markersize=3) # # plt.xlim([tws[0]-10, tws[1]+10]) # plt.xlabel('time[ms]', fontsize=fontsize) # plt.ylabel('prob states', fontsize=fontsize) #plt.plot(x, X, '-k') #plt.scatter(x, X, c=Z, s=50, cmap=discrete_cmap(N, 'brg')) #plt.colorbar(ticks=range(N)) if not(separation is None): n_sep = len(separation) for i_sep, sep_i in enumerate(np.concatenate(([tws[0]],separation[:-1]))): # for i_fr, fr_i in enumerate(text[i_sep]): # plt.text(sep_i, 1+(i_fr*.02), np.around(fr_i, decimals=1), fontsize=8) ax1.text(sep_i, len(X)+1.1, text[i_sep], fontsize=fontsize)#1.02 in ax2 separation = np.reshape(np.array(separation, dtype=float),[1,n_sep]) x_sep = np.repeat(separation,2,0) y_sep = np.vstack([np.zeros([1,n_sep]), np.ones([1,n_sep])]) ax2.plot(x_sep, y_sep, 'k--', linewidth=linewidth, alpha=0.7) #plt.show() return fig, ax1, ax2, fontsize
from matplotlib_venn import venn2, venn2_circles import json from PIL import Image import webbrowser from wordcloud import WordCloud, STOPWORDS import subprocess 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],
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)
#----------------------------------------------------------------------------- # Solve the model and display the result #----------------------------------------------------------------------------- # Solve model print("Solving model....") msol = mdl.solve(TimeLimit=20, LogPeriod=50000) print("Solution: ") msol.print_solution() if msol and visu.is_visu_enabled(): import matplotlib.pyplot as plt import matplotlib.cm as cm from matplotlib.patches import Polygon # Plot external square print("Plotting squares....") fig, ax = plt.subplots() plt.plot((0, 0), (0, SIZE_SQUARE), (SIZE_SQUARE, SIZE_SQUARE), (SIZE_SQUARE, 0)) for i in range(len(SIZE_SUBSQUARE)): # Display square i sx, sy = msol.get_var_solution(vx[i]), msol.get_var_solution(vy[i]) (sx1, sx2, sy1, sy2) = (sx.get_start(), sx.get_end(), sy.get_start(), sy.get_end()) poly = Polygon([(sx1, sy1), (sx1, sy2), (sx2, sy2), (sx2, sy1)], fc=cm.Set2(float(i) / len(SIZE_SUBSQUARE))) ax.add_patch(poly) # Display identifier of square i at its center ax.text(float(sx1 + sx2) / 2, float(sy1 + sy2) / 2, str(SIZE_SUBSQUARE[i]), ha='center', va='center') plt.margins(0) plt.show()
def plot_dendrogram(self,cutoff=0.,method='ward', leafname='new', save=None): "compute and plot hierarchical clustering" ax = plt.gca() for axis in ['top','bottom','left','right']: ax.spines[axis].set_linewidth(0) ax.spines[axis].set_zorder(0) flat_dist = self.mdist[ np.triu_indices(len(self.mdist),1) ]/self.mdist.max() linked = linkage(flat_dist, method) label_list = np.arange(len(self.mdist)) if leafname == 'new': labs = np.copy(self.mnrefs) elif leafname == 'old': labs = np.copy(self.mrefs) my_palette = cm.Set2(np.linspace(0,1,len(self.col2lab))) hierarchy.set_link_color_palette([mplc.rgb2hex(rgb[:3]) for rgb in my_palette]) self.dendro = dendrogram(linked, orientation='top', labels=label_list, distance_sort='descending', color_threshold=cutoff, show_leaf_counts=True, above_threshold_color='black' ) scramble = self.mcol[self.dendro['ivl']] labrable = labs[self.dendro['ivl']] cmap = cm.get_cmap('Spectral') clist = list(set(self.mcol)) col = [ cmap(i*1./(max(clist))) for i in range(max(clist)+1) ] leaves = np.arange(len(self.mdist))*10 + 5 for i in clist: i_leaves = leaves[scramble==i] plt.plot(i_leaves, [0]*len(i_leaves), 'o', mec='none', c=col[i], ms=10.) for c in range(max(clist)+1): plt.plot([],[],marker='o',ms=10,mew=0,c=col[c],lw=0, label=self.col2lab[c]) plt.xticks(leaves,labrable,fontsize=15) plt.legend(loc=2) ax.set_ylim(bottom=-0.2) plt.tight_layout() if save: plt.savefig(save, transparent=True) return self.dendro