def combine_pngs(measure, surface, output_dir, cortex_style): ''' Find four images and combine them into one nice picture ''' figsize = (5, 4) fig = plt.figure(figsize=figsize, facecolor='white') grid = gridspec.GridSpec(2, 2) grid.update(left=0, right=1, top=1, bottom=0.08, wspace=0, hspace=0) f_list = [ '_'.join([ os.path.join(output_dir, measure), 'lh', surface, cortex_style, 'lateral.png' ]), '_'.join([ os.path.join(output_dir, measure), 'rh', surface, cortex_style, 'lateral.png' ]), '_'.join([ os.path.join(output_dir, measure), 'lh', surface, cortex_style, 'medial.png' ]), '_'.join([ os.path.join(output_dir, measure), 'rh', surface, cortex_style, 'medial.png' ]) ] # Plot each figure in turn for g_loc, f in zip(grid, f_list): ax = plt.Subplot(fig, g_loc) fig.add_subplot(ax) img = mpimg.imread(f) # Crop the figures appropriately # NOTE: this can change depending on which system you've made the # images on originally - it's a bug that needs to be sorted out! if 'lateral' in f: img_cropped = img[75:589, 55:(-50), :] else: img_cropped = img[45:600, 25:(-25), :] ax.imshow(img_cropped, interpolation='none') ax.set_axis_off() # Add the bottom of one of the images as the color bar # at the bottom of the combo figure grid_cbar = gridspec.GridSpec(1, 1) grid_cbar.update(left=0, right=1, top=0.08, bottom=0, wspace=0, hspace=0) ax = plt.Subplot(fig, grid_cbar[0]) fig.add_subplot(ax) img = mpimg.imread(f) img_cbar = img[600:, :] ax.imshow(img_cbar, interpolation='none') ax.set_axis_off() # Save the figure filename = os.path.join( output_dir, '{}_{}_{}_combined.png'.format(measure, surface, cortex_style)) print filename fig.savefig(filename, bbox_inches=0, dpi=300)
def add_extra_fig3_bits(paper_dir, fig): import os # Add in the MBP correlations # at the top on the left mbp_fig = os.path.join(paper_dir, 'COMBINED_FIGURES', 'COVARS_none', 'MBPvsMT14.png') # Set up the grid grid = gridspec.GridSpec(1, 1) grid.update(left=0.03, right=0.55, top=0.99, bottom=0.8, wspace=0, hspace=0) ax = plt.Subplot(fig, grid[0]) fig.add_subplot(ax) # Show the figure img = mpimg.imread(mbp_fig) ax.imshow(img, interpolation='none') ax.axis('off') # Next add the permutation tests # at the bottom on the left # Set up the grid grid = gridspec.GridSpec(2, 1) grid.update(left=0.55, right=0.99, top=0.43, bottom=0, wspace=0, hspace=0) ax_list = [] for i, g_loc in enumerate(grid): ax_list += [plt.Subplot(fig, g_loc)] fig.add_subplot(ax_list[-1]) gene_dict = {'OL': 'Oligodendrocytes', 'SZ': 'Schizophrenia'} for i, gene in enumerate(sorted(list(gene_dict.keys()))): gene_fig = os.path.join(paper_dir, 'COMBINED_FIGURES', 'COVARS_none', 'CandidateGenes_{}.png'.format(gene)) ax = ax_list[i] img = mpimg.imread(gene_fig) ax.imshow(img, interpolation='none') ax.axis('off') # Add in a label for the cohort ax.text(-0.05, 0.55, gene_dict[gene], horizontalalignment='left', verticalalignment='center', rotation=90, transform=ax.transAxes, fontsize=8) return fig
def combine_pngs(measure1, measure2, surface, stat, fs_rois_dir): figsize = (4.5, 4) fig = plt.figure(figsize=figsize, facecolor='white') grid = gridspec.GridSpec(2, 2) grid.update(left=0, right=1, top=1, bottom=0.08, wspace=0, hspace=0) f_list = [ '_'.join([ os.path.join(fs_rois_dir, measure1), 'lh', surface, stat, measure2, 'lateral.png' ]), '_'.join([ os.path.join(fs_rois_dir, measure1), 'rh', surface, stat, measure2, 'lateral.png' ]), '_'.join([ os.path.join(fs_rois_dir, measure1), 'lh', surface, stat, measure2, 'medial.png' ]), '_'.join([ os.path.join(fs_rois_dir, measure1), 'rh', surface, stat, measure2, 'medial.png' ]) ] for g_loc, f in zip(grid, f_list): ax = plt.Subplot(fig, g_loc) fig.add_subplot(ax) img = mpimg.imread(f) if 'lateral' in f: img_cropped = img[58:598, 60:740, :] else: img_cropped = img[28:618, 60:740, :] ax.imshow(img_cropped, interpolation='none') ax.set_axis_off() grid_cbar = gridspec.GridSpec(1, 1) grid_cbar.update(left=0, right=1, top=0.08, bottom=0, wspace=0, hspace=0) ax = plt.Subplot(fig, grid_cbar[0]) fig.add_subplot(ax) img = mpimg.imread(f) img_cbar = img[605:, :] ax.imshow(img_cbar, interpolation='none') ax.set_axis_off() filename = os.path.join( fs_rois_dir, '{}_{}_{}_{}_combined.png'.format(measure1, surface, stat, measure2)) print filename fig.savefig(filename, bbox_inches=0, dpi=300)
def add_figure3_parts(paper_dir, fig): import os # Set up the grid grid = gridspec.GridSpec(3, 1) grid.update(left=0.03, right=0.55, top=0.8, bottom=0.0, wspace=0, hspace=0) ax_list = [] for i, g_loc in enumerate(grid): ax_list += [plt.Subplot(fig, g_loc)] fig.add_subplot(ax_list[-1]) # Loop through the three cohorts for i, cohort in enumerate(['DISCOVERY', 'VALIDATION', 'COMPLETE']): figure3 = os.path.join(paper_dir, cohort, 'FIGS', 'COVARS_none', 'Figure3.png') ax = ax_list[i] # Show the figure, excluding the first panel img = mpimg.imread(figure3) img_cropped = img[:1200, :, :] ax.imshow(img_cropped, interpolation='none') ax.axis('off') # Add in a label for the cohort ax.text(-0.05, 0.5, cohort.title(), horizontalalignment='left', verticalalignment='center', rotation=90, transform=ax.transAxes, fontsize=10) return fig
def add_extra_fig4_bits(paper_dir, fig): import os # Set up the grid grid = gridspec.GridSpec(1, 3) grid.update(left=0.01, right=0.99, top=1.0, bottom=0.75, wspace=0, hspace=0) ax_list = [] for i, g_loc in enumerate(grid): ax_list += [plt.Subplot(fig, g_loc)] fig.add_subplot(ax_list[-1]) # Loop through the three cohorts for i, cohort in enumerate(['DISCOVERY', 'VALIDATION', 'COMPLETE']): figure4 = os.path.join(paper_dir, cohort, 'FIGS', 'NetworkSummary.png') ax = ax_list[i] # Show the figure, excluding the first panel img = mpimg.imread(figure4) ax.imshow(img, interpolation='none') ax.axis('off') # Add in a label for the cohort ax.text(0.5, 0, cohort.title(), horizontalalignment='center', verticalalignment='top', transform=ax.transAxes, fontsize=10) return fig
def add_four_hor_brains(grid, f_list, fig): ''' Take the four pysurfer views (left lateral, left medial, right medial and right lateral) and arrange them in a row according to the grid positions given by grid grid : the gridspec list of grid placements f_list : list of four file pysurfer image files big_fig : the figure to which you're adding the images # THIS WAS UPDATED TO INCLUDE PLOTTING IN A GRID # Should probably change the function name! ''' for g_loc, f in zip(grid, f_list): img = mpimg.imread(f) # Crop the figures appropriately # NOTE: this can change depending on which system you've made the # images on originally - it's a bug that needs to be sorted out! if 'lateral' in f: img_cropped = img[115:564, 105:(-100), :] else: img_cropped = img[90:560, 60:(-55), :] # Add an axis to the figure ax_brain = plt.Subplot(fig, g_loc) fig.add_subplot(ax_brain) # Show the brain on this axis ax_brain.imshow(img_cropped, interpolation='none') ax_brain.set_axis_off() return fig
def combine_pngs(result_file, surface): figsize = (4.5, 4) fig = plt.figure(figsize=figsize, facecolor='white') grid = gridspec.GridSpec(2, 2) grid.update(left=0, right=1, top=1, bottom=0.08, wspace=0, hspace=0) f_list = [ '{}_{}_{}_{}.png'.format(result_file.strip('.nii.gz'), 'lh', surface, 'lateral'), '{}_{}_{}_{}.png'.format(result_file.strip('.nii.gz'), 'rh', surface, 'lateral'), '{}_{}_{}_{}.png'.format(result_file.strip('.nii.gz'), 'lh', surface, 'medial'), '{}_{}_{}_{}.png'.format(result_file.strip('.nii.gz'), 'rh', surface, 'medial') ] for g_loc, f in zip(grid, f_list): ax = plt.Subplot(fig, g_loc) fig.add_subplot(ax) img = mpimg.imread(f) if 'lateral' in f: img_cropped = img[58:598, 60:740, :] else: img_cropped = img[18:628, 15:785, :] ax.imshow(img_cropped, interpolation='none') ax.set_axis_off() grid_cbar = gridspec.GridSpec(1, 1) grid_cbar.update(left=0, right=1, top=0.08, bottom=0, wspace=0, hspace=0) ax = plt.Subplot(fig, grid_cbar[0]) fig.add_subplot(ax) img = mpimg.imread(f) img_cbar = img[605:, :] ax.imshow(img_cbar, interpolation='none') ax.set_axis_off() filename = '{}_{}_{}.png'.format(result_file.strip('.nii.gz'), surface, 'combined') print filename fig.savefig(filename, bbox_inches=0, dpi=300)
def add_colorbar(grid, big_fig, cmap_name, y_min=0, y_max=1, cbar_min=0, cbar_max=1, vert=False, label=None, show_ticks=True, pad=0): # Set the seaborn context and style sns.set(style="white") sns.set_context("poster", font_scale=3) ''' Add a colorbar to the big_fig in the location defined by grid grid : grid spec location to add colormap big_fig : figure to which colorbar will be added cmap_name : name of the colormap x_min : the minimum value to plot this colorbar between x_max : the maximum value to plot this colorbar between cbar_min : minimum value for the colormap (default 0) cbar_max : maximum value for the colormap (default 1) vert : whether the colorbar should be vertical (default False) label : the label for the colorbar (default: None) ticks : whether to put the tick values on the colorbar (default: True) pad : how much to shift the colorbar label by (default: 0) ''' import matplotlib as mpl from matplotlib.colors import LinearSegmentedColormap # Add an axis to the big_fig ax_cbar = plt.Subplot(big_fig, grid) big_fig.add_subplot(ax_cbar) # Normalise the colorbar so you have the correct upper and # lower limits and define the three ticks you want to show norm = mpl.colors.Normalize(vmin=cbar_min, vmax=cbar_max) if show_ticks: ticks = [y_min, np.average([y_min, y_max]), y_max] else: ticks=[] # Figure out the orientation if vert: orientation='vertical' rotation=270 else: orientation='horizontal' rotation=0 # Add in your colorbar: cb = mpl.colorbar.ColorbarBase(ax_cbar, cmap=cmap_name, norm=norm, orientation=orientation, ticks=ticks, boundaries=np.linspace(y_min, y_max, 300)) if label: cb.set_label(label, rotation=rotation, labelpad=pad) return big_fig
def add_background(fig, grid): ax = plt.Subplot(fig, grid[0]) fig.add_subplot(ax) # Add a black background black = ax.imshow(np.ones([100, 100]), interpolation='none', cmap='gray', aspect='auto') # Turn off axis labels ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) ax.set_frame_on(False) return fig
def add_header(fig, grid): ax = plt.Subplot(fig, grid[0]) fig.add_subplot(ax) # The header simply says: header_text = "Diffusion Tensor Imaging Quality Report\n\nSubID:____________ Date:____________" ax.text(0.05, 0.5, header_text, transform=ax.transAxes, fontsize=14, horizontalalignment='left', verticalalignment='center') # On the right we'll add two options: quality_text = "Pass" ax.text(0.82, 0.55, quality_text, transform=ax.transAxes, fontsize=18, horizontalalignment='right', verticalalignment='bottom') ax.add_patch( patches.Rectangle((0.84, 0.55), 0.1, 0.35, color='black', fill=False)) quality_text = "Fail" ax.text(0.82, 0.15, quality_text, transform=ax.transAxes, fontsize=18, horizontalalignment='right', verticalalignment='bottom') ax.add_patch( patches.Rectangle((0.84, 0.15), 0.1, 0.35, color='black', fill=False)) # Turn off axis labels ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) ax.set_frame_on(False) return fig
def plot_movement_params(dti_dir, fig, grid): measures = ['abs', 'rel'] measure_suffixes = ['', '_b0', '_notb0'] # Loop through the measure suffixes ('', '_b0', '_notb0') # which you can think of as the groups of volumes that are being considered # and find the data from each of thoese files for i, suffix in enumerate(measure_suffixes): ax = plt.Subplot(fig, grid[i]) fig.add_subplot(ax) # Read in the files disp = pd.read_csv(os.path.join(dti_dir, 'ec_disp{}.txt'.format(suffix)), delimiter=' ', header=None, names=['abs' + suffix, 'rel' + suffix], na_values='.') # Loop through the three different values that you want to know # for the two different measures (abs and rel) for measure in measures: ax.plot(disp[measure + suffix][disp[measure + suffix].notnull()], label=measure) # Label the x axis according to which plot this is: if suffix == '': ax.set_xlabel('Volume Number') elif suffix == '_b0': ax.set_xlabel('B0 Volume Number') else: ax.set_xlabel('Diff weighted Volume Number') # Set the y axis to always between 0 and 3 ax.set_ylim(0, 3) # Only label the first y axis if i == 0: # And label the yaxis ax.set_ylabel('Displacement (mm)') # Add a legend leg = ax.legend(loc=2, fontsize=8) leg.get_frame().set_alpha(0.5) return fig
def add_parcellation_brains(paper_dir, fig): parcellation_brains = os.path.join( paper_dir, 'COMBINED_FIGURES', 'PARCELLATION', 'PNGS', 'Parcellation_308_random_matched_hemis_FourHorBrains.png') img = mpimg.imread(parcellation_brains) # Set up the grid grid = gridspec.GridSpec(1, 1) grid.update(left=0.01, right=0.99, top=0.72, bottom=0.59, wspace=0, hspace=0) ax_brains = plt.Subplot(fig, grid[0]) fig.add_subplot(ax_brains) ax_brains.imshow(img, interpolation='none') ax_brains.axis('off') return fig
def plotSingleLinearFit(fig, gridloc, pars, results, data, trainingsInd, testInd, behaviors): inner_grid = gridspec.GridSpecFromSubplotSpec(len(behaviors), 3, subplot_spec=gridloc, hspace=1, wspace=0.25, width_ratios=[3,1,1]) for lindex, label in enumerate(behaviors): #weights, intercept, alpha, _,_ = resultSet[key][fitmethod][label] weights = results[label]['weights'] intercept = results[label]['intercepts'] if pars['useRank']: x = data['Neurons']['rankActivity'] else: x = data['Neurons']['Activity'] y = data['Behavior'][label] # calculate y from model yPred = np.dot(weights, x) + intercept yTrain = np.ones(yPred.shape)*np.nan yTrain[trainingsInd] = yPred[trainingsInd] yTest = np.ones(yPred.shape)*np.nan yTest[testInd] = yPred[testInd] #if random=='random': # yTest = yPred # plot training and test set behavior and prediction ax1 = plt.Subplot(fig, inner_grid[lindex, 0]) ax1.plot(data['Neurons']['Time'], yTrain, color=colorBeh[label], label = 'Training', alpha =0.4, lw=2) ax1.plot(data['Neurons']['Time'], y, color=colorBeh[label], label = 'Behavior', lw=1) ax1.plot(data['Neurons']['Time'], yTest, color=colorPred[label], label = r'$R^2$ {0:.2f}'.format(results[label]['scorepredicted']), lw=1) ax1.set_xlim(np.percentile(data['Neurons']['Time'], [0,100])) ax1.set_ylabel(names[label]) if lindex==len(behaviors)-1: ax1.set_xlabel('Time (s)') ax1.legend(loc=(0.0,0.9), ncol = 2) fig.add_subplot(ax1) # show how predictive each additional neuron is ax4 = plt.Subplot(fig, inner_grid[lindex, 2]) ax4.plot(results[label]['cumulativeScore'], color=colorPred[label],marker='o', markerfacecolor="none",markersize=5) ax4.plot(results[label]['individualScore'], color=colorBeh[label],marker='o', markerfacecolor="none", markersize=5) ax4.set_ylabel(r'$R^2$ score') if lindex==len(behaviors)-1: ax4.set_xlabel('Number of neurons') fig.add_subplot(ax4) # plot weights ax3 = plt.Subplot(fig, inner_grid[:,1]) for lindex, label in enumerate(behaviors): weights = results[label]['weights'] if lindex == 0: indices = np.arange(len(x)) indices = np.argsort(weights) rank = np.arange(0, len(weights)) ax3.fill_betweenx(rank, np.zeros(len(weights)),weights[indices]/np.max(weights), step='pre', color=colorBeh[label], alpha = 0.5) ax3.set_ylabel('Neuron weights') ax3.spines['left'].set_visible(False) ax3.set_yticks([]) fig.add_subplot(ax3)
def plot_dti_slices(background_file, overlay_file, fig, grid, ax_name_list, cmap='jet'): # LOAD THE DATA bg_img = nib.load(background_file) bg = bg_img.get_data() if len(bg.shape) == 4: bg = bg[:, :, :, 0] overlay_img = nib.load(overlay_file) overlay = overlay_img.get_data() # Make sure all data is float: bg = bg / 1. overlay = overlay / 1. # Scale the data by its maximum bg = bg / bg.max() overlay = overlay / overlay.max() # Now we're going to loop through the different slice orientations for i, axis_name in enumerate(ax_name_list): if axis_name == 'axial': # Align so that right is right overlay_plot = np.rot90(overlay) overlay_plot = np.fliplr(overlay_plot) bg_plot = np.rot90(bg) bg_plot = np.fliplr(bg_plot) elif axis_name == 'coronal': overlay_plot = np.rot90(overlay) bg_plot = np.rot90(bg) overlay_plot = np.flipud(np.swapaxes(overlay_plot, 0, 2)) bg_plot = np.flipud(np.swapaxes(bg_plot, 0, 2)) elif axis_name == 'sagittal': overlay_plot = np.flipud(np.swapaxes(overlay, 0, 2)) bg_plot = np.flipud(np.swapaxes(bg, 0, 2)) n = (np.float(bg_plot.shape[1]) / bg_plot.shape[2]) * (np.float(figsize[0]) / (0.15 * figsize[1])) n_floor = np.int(np.floor(n)) inner_grid = gridspec.GridSpecFromSubplotSpec(1, n_floor, subplot_spec=grid[i], wspace=0.0, hspace=0.0) for j, slice_id in enumerate( np.linspace(0, bg_plot.shape[2], n_floor + 2)[1:-1]): bg_slice = bg_plot[:, :, slice_id] overlay_slice = overlay_plot[:, :, slice_id] ax = plt.Subplot(fig, inner_grid[j]) fig.add_subplot(ax) # Add a black background black = ax.imshow(np.ones_like(bg_slice), interpolation='none', cmap='gray') # Mask the data m_overlay_slice = np.ma.masked_where(overlay_slice == 0, overlay_slice) # First show the background slice im1 = ax.imshow(bg_slice, interpolation='none', cmap='gray', vmin=0, vmax=1) # Then overlay the overlay_slice im2 = ax.imshow(m_overlay_slice, interpolation='none', cmap=cmap, vmin=0, vmax=1, alpha=0.3) # Turn off axis labels ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) ax.set_frame_on(False) return fig
def tensor_histogram(fa_file, mo_file, sse_file, wm_mask_file, fig, grid): # Load in the data fa_img = nib.load(fa_file) fa = fa_img.get_data() mo_img = nib.load(mo_file) mo = mo_img.get_data() sse_img = nib.load(sse_file) sse = sse_img.get_data() wm_mask_img = nib.load(wm_mask_file) wm_mask = wm_mask_img.get_data() wm_mask[wm_mask > 0] = 1 # Mask the fa data with the white matter mask # so we're only looking inside the mask fa = fa * wm_mask # Add a subplot to the first space in the grid # and enter a histogram of FA values ax = plt.Subplot(fig, grid[0]) fig.add_subplot(ax) ax.hist(fa[fa > 0].reshape(-1), bins=np.linspace(0, 1, 100), color='green', histtype='stepfilled') # Label the x axis: ax.set_xlabel('Fractional Anisotropy') # Set the y axis to always between 0 and 2500 ax.set_ylim(0, 2500) # Adjust the power limits so that you use scientific notation on the y axis ax.ticklabel_format(style='sci', axis='y') ax.yaxis.major.formatter.set_powerlimits((-3, 3)) # Only label this first y axis as they're all the same ax.set_ylabel('Number of voxels') # Add a subplot to the second space in the grid # and plot a histogram of mode values ax = plt.Subplot(fig, grid[1]) fig.add_subplot(ax) ax.hist(mo[fa > 0].reshape(-1), bins=np.linspace(-1, 1, 100), color='orange', histtype='stepfilled') # Label the x axes: ax.set_xlabel('Mode of Anisotropy') # Set the y axis to always between 0 and 3500 ax.set_ylim(0, 3500) # Adjust the power limits so that you use scientific notation on the y axis #plt.ticklabel_format(style='sci', axis='y') ax.yaxis.major.formatter.set_powerlimits((-3, 3)) # Add a subplot to the third space in the grid # and plot a histogram of sum of square errors # Note that low values are very good - they indicate voxels # that have a good fit to the diffusion tensor model. # The y-axis is therefore limited so that the histogram highlights # "bad" fit voxels. ax = plt.Subplot(fig, grid[2]) fig.add_subplot(ax) ax.hist(sse[fa > 0].reshape(-1), bins=np.linspace(0, 5, 100), color='red', histtype='stepfilled') # Label the x axis: ax.set_xlabel('Sum of Square Errors') # Set the y axis to always between 0 and 3500 ax.set_ylim(0, 100) return fig
## plot neurons against transformed neurons fig3 = plt.figure('Transformed neurons', (13.6, nWorms * 3.4)) outer_grid2 = mp.gridspec.GridSpec(nWorms, 1, hspace=0.25, wspace=0.25) for kindex, key in enumerate(keyList): neuro = dataSets[key]['Neurons'] whichNeurons = range(0, len(neuro['rankActivity']), 15) inner_grid = mp.gridspec.GridSpecFromSubplotSpec( 1, len(whichNeurons), subplot_spec=outer_grid2[kindex], hspace=0.25, wspace=0.5) for i, n in enumerate(whichNeurons): ax1 = plt.Subplot(fig3, inner_grid[i]) fig3.add_subplot(ax1) ax1.set_title('Neuron ID {}'.format(n)) ax1.scatter(neuro['Activity'][n], neuro['rankActivity'][n] / 1.0 / len(neuro['rankActivity']), s=2, alpha=0.2) ax1.set_ylabel('rank-transformed') ax1.set_xlabel('raw activity') ax1.set_xlim([ np.percentile(neuro['Activity'], [2.5]), np.percentile(neuro['Activity'], [99.5]) ]) ax1.set_ylim([0, 1]) outer_grid2.tight_layout(fig3)
plt.subplots_adjust(right = 0.7) plt.savefig(fig_save_dir + 'phase_dynamics_est.png', bbox_inches="tight") plt.savefig(fig_save_dir + 'phase_dynamics_est.svg', bbox_inches="tight") plt.savefig(fig_save_dir + 'phase_dynamics_est.eps', bbox_inches="tight") plt.show() #%% idx = np.where(C > Cth)[0] fig = plt.figure(figsize=(15, 12)) outer = gridspec.GridSpec(2, 1, wspace=0.25, hspace=0.5, height_ratios=[1,0.8]) vmin = -0.7 vmax = 0.7 inner = gridspec.GridSpecFromSubplotSpec(2, 5, subplot_spec=outer[0], wspace=0.2, hspace=0.5, width_ratios=[0.1,1,1,1,0.08]) tmp = plt.Subplot(fig, inner[:,State+1]) ax_cb = fig.add_subplot(tmp) cbar_info = [False, {"orientation":"vertical", 'label': 'Coupling strength (a.u.)'}, ax_cb] for state in range(State): ax = plt.Subplot(fig, inner[0,state+1]) vis_heatmap(K_tr[:,:,state], vmin, vmax, ax, np.array(['Segment %d\n'%(state+1), 'osci. $j$', 'osci. $i$']), cbar_info, linewidths = 0.0, fontsize=28) fig.add_subplot(ax) if state == 0: ax_pos = ax.get_position() fig.text(ax_pos.x1 - .22, ax_pos.y1-0.08, 'true') fig.text(ax_pos.x1 - .3, ax_pos.y1, 'A', fontsize=40) fig.text(ax_pos.x1 - .3, ax_pos.y1-0.42, 'B', fontsize=40) ax = plt.Subplot(fig, inner[1,state+1]) if state == State-1:
plt.savefig(fig_save_dir + 'comp_est_error.png', bbox_inches="tight") plt.savefig(fig_save_dir + 'comp_est_error.svg', bbox_inches="tight") plt.savefig(fig_save_dir + 'comp_est_error.eps', bbox_inches="tight") plt.show() #%% cbar_info = [False, {"orientation": "horizontal"}, ax_cb] fig = plt.figure(figsize=(12, 8)) outer = gridspec.GridSpec(4, 2, wspace=0.3, hspace=0.2, height_ratios=[1, 1, 1, 0.08]) tmp = plt.Subplot(fig, outer[6:]) ax_cb = fig.add_subplot(tmp) vmin = -0.5 vmax = 0.5 for i in range(len(Ncond)): if i == 4: cbar_info = [ True, { "orientation": "horizontal", 'label': 'Coupling strength (a.u.)' }, ax_cb ] else: cbar_info = [
ax2.axvspan(x[0], x[1], color = col, label='State' + str(sgm+1)) ax2.set_yticks([]) ax2.set_xlabel('# sample') ax2.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0) plt.savefig(fig_save_dir + 'exact_state_changes.png', bbox_inches="tight") plt.savefig(fig_save_dir + 'exact_state_changes.svg', bbox_inches="tight") plt.savefig(fig_save_dir + 'exact_state_changes.eps', bbox_inches="tight") plt.show() #%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% fig = plt.figure(figsize=(15, 18)) outer = gridspec.GridSpec(2, 1, wspace=0.25, hspace=0.3, height_ratios=[1,0.4]) inner = gridspec.GridSpecFromSubplotSpec(3, 5, subplot_spec=outer[0], wspace=0.2, hspace=0.5, width_ratios=[0.1,1,1,1,0.08]) tmp = plt.Subplot(fig, inner[:,State+1]) ax_cb = fig.add_subplot(tmp) cbar_info = [False, {"orientation":"vertical", 'label': 'Coupling strength (a.u.)'}, ax_cb] for state in range(State): ax = plt.Subplot(fig, inner[0,state+1]) vis_heatmap(K1_tr[:,:,state], vmin, vmax, ax, np.array(['Segment %d\n $a_{ij}$'%(state+1), 'osci. $j$', 'osci. $i$']), cbar_info, linewidths = 0.001, fontsize=28) fig.add_subplot(ax) if state == 0: ax_pos = ax.get_position() fig.text(ax_pos.x1 - .3, ax_pos.y1+0.03, 'A', fontsize=40) fig.text(ax_pos.x1 - .3, ax_pos.y1-0.5, 'B', fontsize=40) ax = plt.Subplot(fig, inner[1,state+1]) vis_heatmap(K2_tr[:,:,state], vmin, vmax, ax, np.array(['\n $b_{ij}$', 'osci. $j$', 'osci. $i$']), cbar_info, linewidths = 0.001, fontsize=28) fig.add_subplot(ax)