def print_matrix(row, col, row_label, col_label, matrix_1, matrix_2, number, same_row_col): f, ax = plt.subplots(2, sharex = True) ax[0] = plt.subplot2grid((2,2), (0,0), colspan = 2) ax[1] = plt.subplot2grid((2,2), (1,0), colspan = 2) # Assigns color according to values in fitness_heat arrays norm = MidpointNormalize(midpoint=0) #im1 = ax[0].imshow(matrix_1, cmap=plt.cm.seismic, interpolation='none') im1 = ax[0].imshow(matrix_1, norm=norm, cmap=plt.cm.seismic, interpolation='none') divider1 = make_axes_locatable(ax[0]) cax1 = divider1.append_axes("right", size="2%", pad=0.05) im2 = ax[1].imshow(matrix_2, cmap=plt.cm.seismic, interpolation='none') #im2 = ax[1].imshow(matrix_2, norm=norm, cmap=plt.cm.seismic, interpolation='none') divider2 = make_axes_locatable(ax[1]) cax2 = divider2.append_axes("right", size="2%", pad=0.05) # Sorting out labels for y-axis in correct order and placing in new list 'yax' yax1 = sorted(number.items(), key=lambda (k, v): v) yax = [] for item in yax1: if item[0] =='STOP': yax.append ('*') else: yax.append (item[0]) if same_row_col == True: xax = yax x = np.arange(0, row+0.5, 1) ax[0].set_xticks(x) ax[0].set_xticklabels(xax, rotation='horizontal', fontsize = 10) ax[0].set_xlabel(row_label) ax[1].set_xticks(x) ax[1].set_xticklabels(xax, rotation='horizontal', fontsize = 10) ax[1].set_xlabel(row_label) else: x = np.arange(0.5, col+0.5, 5) xlab = np.arange(1, col, 5) plt.xticks(x, xlab, rotation='horizontal') ax[1].set_xlabel(col_label) # Setting up y-axis ticks...want AA labels, centered y = np.arange(0, row, 1) ax[0].set_yticks(y) ax[0].set_yticklabels(yax, rotation='horizontal', fontsize = 10) ax[0].set_ylabel(row_label) ax[1].set_yticks(y) ax[1].set_yticklabels(yax, rotation='horizontal', fontsize = 10) ax[1].set_ylabel(row_label) # Setting up x-axis ticks...want residue number, centered # Limit axes to appropriate values plt.axis([0, col, 0, row]) plt.colorbar(im1, cax = cax1) plt.colorbar(im2, cax = cax2) plt.show()
def plot_residuals(directory): residuals = [] for directory in _get_cc_dirs(directory): residual_file = directory + os.sep + 'results/residuals.dat' residuals.append(np.loadtxt(residual_file)) all_residuals = np.array(residuals) nr_f = all_residuals.shape[1] / 2 fig, axes = plt.subplots(1, 2, figsize=(6, 2.5)) ax = axes[0] im = ax.imshow(all_residuals[:, 0:nr_f], interpolation='none') divider = make_axes_locatable(ax) ax_cb = divider.new_horizontal(size="5%", pad=0.05) fig.add_axes(ax_cb) fig.colorbar(im, cax=ax_cb) ax.set_xlabel('frequency') ax.set_title(r'Magnitude $\Delta(log(R))$') ax = axes[1] im = ax.imshow(all_residuals[:, nr_f:], interpolation='none') divider = make_axes_locatable(ax) ax_cb = divider.new_horizontal(size="5%", pad=0.05) fig.add_axes(ax_cb) fig.colorbar(im, cax=ax_cb) ax.set_xlabel('frequency') ax.set_title(r'Phase $\Delta \phi$') fig.tight_layout() fig.savefig('residuals.png', dpi=300)
def show(self): nclasses = len(self._landclass) gs=plt.GridSpec(nclasses, 2) row = 0 fig=plt.figure() for c in self._landclass: ax=fig.add_subplot(gs[row,0], title=c) im=ax.imshow(self._landclass[c].get_raster()) from mpl_toolkits.axes_grid1 import make_axes_locatable divider = make_axes_locatable(plt.gca()) cax = divider.append_axes("right", "5%", pad="3%") cb=fig.colorbar(im,cax=cax) ax=fig.add_subplot(gs[row,1],title='Classified '+c) im=ax.imshow(self._landclass[c].get_classraster()) divider = make_axes_locatable(plt.gca()) cax = divider.append_axes("right", "5%", pad="3%") cb=fig.colorbar(im,cax=cax) cb.set_ticks( list(range(1,self._landclass[c].get_nclasses()+1))) cb.set_ticklabels(self._landclass[c].get_classes_str()) row +=1 fig.tight_layout()
def plot_thsections(dbz,vvel,ht,dayt,**kwargs): fig,ax = plt.subplots(2,1,sharex=True) 'colormap for vvel' orig_cmap = cm.bwr shifted_cmap = shiftedColorMap(orig_cmap, midpoint=0.7, name='shifted') ' add images and colorbar' im0=ax[0].imshow(dbz,interpolation='none',cmap='nipy_spectral',vmin=-20,vmax=60,aspect='auto',origin='lower') im1=ax[1].imshow(vvel,interpolation='none',cmap=shifted_cmap,vmin=-10,vmax=4,aspect='auto',origin='lower') divider0 = make_axes_locatable(ax[0]) cax0 = divider0.append_axes("right", size="2%", pad=0.05) cbar0 = plt.colorbar(im0, cax=cax0) divider1 = make_axes_locatable(ax[1]) cax1 = divider1.append_axes("right", size="2%", pad=0.05) cbar1 = plt.colorbar(im1, cax=cax1) if 'echotop' in kwargs: echot=kwargs['echotop'] ax[0].plot(echot,color='k') format_yaxis(ax[0],ht) format_yaxis(ax[1],ht) format_xaxis(ax[1], dayt, minutes_tick=30, labels=True) ax[1].invert_xaxis() ax[0].set_ylabel('Hgt MSL [km]') ax[1].set_ylabel('Hgt MSL [km]') ax[1].set_xlabel(r'$\Leftarrow$'+' Time [UTC]') plt.subplots_adjust(hspace=0.05) plt.suptitle('SPROF observations. Date: '+dayt[0].strftime('%Y-%b')) plt.draw()
def compare(data, model, res, chi, filename): head = np.percentile(data, 99.9) toe = np.percentile(data, 0.1) chirange = 5. # head*0.05 # np.percentile(data, 9.3) resrange = (head-toe)*0.5 # np.percentile(data, 50.0) width, height = np.shape(data) figw, figh = (width/dippy)*2., (height/dippy)*2. fig = plt.figure(figsize=(figw, figh)) # fig = plt.figure(dpi=dippy, figsize=(figw, figh)) gs = gridspec.GridSpec(2, 2) # axr = fig.add_subplot(221) axr = plt.subplot(gs[0]) axr.set_axis_off() axr.set_title(r"Data", fontsize=40) caxr = axr.imshow(data, cmap=plt.cm.gray, vmin=toe, vmax=head) divr = make_axes_locatable(plt.gca()) cbarr = divr.append_axes("right", "5%", pad="3%") fig.colorbar(caxr, cax=cbarr) # axf = fig.add_subplot(222) axf = plt.subplot(gs[1]) axf.set_axis_off() axf.set_title(r"Model Image", fontsize=40) caxf = axf.imshow(model, cmap=plt.cm.gray, vmin=toe, vmax=head) divf = make_axes_locatable(plt.gca()) cbarf = divf.append_axes("right", "5%", pad="3%") fig.colorbar(caxf, cax=cbarf) # axres = fig.add_subplot(223) axres = plt.subplot(gs[2]) axres.set_axis_off() axres.set_title(r"Residual Image",fontsize=40) caxres = axres.imshow(res, cmap=plt.cm.gray, vmin=-resrange, vmax=resrange) divres = make_axes_locatable(plt.gca()) cbarres = divres.append_axes("right", "5%", pad="3%") fig.colorbar(caxres, cax=cbarres) # axchi = fig.add_subplot(224) axchi = plt.subplot(gs[3]) axchi.set_axis_off() axchi.set_title(r"Chi Image", fontsize=40) caxchi = axchi.imshow(chi, cmap=plt.cm.gray, vmin=-chirange, vmax=chirange) divchi = make_axes_locatable(plt.gca()) cbarchi = divchi.append_axes("right", "5%", pad="3%") fig.colorbar(caxchi, cax=cbarchi) # fig.subplots_adjust(hspace=0.001) fig.tight_layout() # fig.savefig(filename, dpi=60., bbox_inches='tight') fig.savefig(filename)
def display_data(data): from mpl_toolkits.axes_grid1 import make_axes_locatable fig, (trans_ax, f_1_ax, f_2_ax) = plt.subplots(ncols=1, nrows=3, sharex=True, constrained_layout=True, figsize=(6, 4)) trans_im = trans_ax.imshow(data.trans, extent=data.extent) trans_divider = make_axes_locatable(trans_ax) trans_ax_cb = trans_divider.new_horizontal(size="3%", pad=0.05) trans_fig = trans_ax.get_figure() trans_fig.add_axes(trans_ax_cb) trans_cb = plt.colorbar(trans_im, cax=trans_ax_cb) trans_cb.ax.set_ylabel(r'$P_{trans}$', rotation=0, labelpad=25, size=15) f_1_im = f_1_ax.imshow(data.f_1.T, extent=data.extent) f_1_divider = make_axes_locatable(f_1_ax) f_1_ax_cb = f_1_divider.new_horizontal(size="3%", pad=0.05) f_1_fig = f_1_ax.get_figure() f_1_fig.add_axes(f_1_ax_cb) f_1_cb = plt.colorbar(f_1_im, cax=f_1_ax_cb) f_1_cb.ax.set_ylabel(r'$P_{f1}$', rotation=0, labelpad=15, size=15) f_2_im = f_2_ax.imshow(data.f_2.T, extent=data.extent) f_2_divider = make_axes_locatable(f_2_ax) f_2_ax_cb = f_2_divider.new_horizontal(size="3%", pad=0.05) f_2_fig = f_2_ax.get_figure() f_2_fig.add_axes(f_2_ax_cb) f_2_cb = plt.colorbar(f_2_im, cax=f_2_ax_cb) f_2_cb.ax.set_ylabel(r'$P_{f2}$', rotation=0, labelpad=13, size=15) f_1_ax.set_ylabel(r'Neutron Angle $\phi$ (rad)') f_2_ax.set_xlabel(r'Detector Angle $\theta$ (rad)') fig.suptitle('Data Sinograms') plt.subplots_adjust(top=0.92, bottom=0.125, left=0.100, right=0.9, hspace=0.2, wspace=0.2)
def display_images(mu_im, mu_f_im, p_im, title='Images'): from mpl_toolkits.axes_grid1 import make_axes_locatable fig, (mu_ax, mu_f_ax, p_ax) = plt.subplots(ncols=1, nrows=3, sharex=True, constrained_layout=True, figsize=(5, 6)) mu_im = mu_ax.imshow(mu_im.data, extent=mu_im.extent) mu_divider = make_axes_locatable(mu_ax) mu_ax_cb = mu_divider.new_horizontal(size="5%", pad=0.05) mu_fig = mu_ax.get_figure() mu_fig.add_axes(mu_ax_cb) mu_cb = plt.colorbar(mu_im, cax=mu_ax_cb) mu_cb.ax.set_ylabel(r'$\mu$', rotation=0, labelpad=10, size=15) mu_f_im = mu_f_ax.imshow(mu_f_im.data, extent=mu_f_im.extent) mu_f_divider = make_axes_locatable(mu_f_ax) mu_f_ax_cb = mu_f_divider.new_horizontal(size="5%", pad=0.05) mu_f_fig = mu_f_ax.get_figure() mu_f_fig.add_axes(mu_f_ax_cb) mu_f_cb = plt.colorbar(mu_f_im, cax=mu_f_ax_cb) mu_f_cb.ax.set_ylabel(r'$\frac{\mu_f}{\mu}$', rotation=0, labelpad=10, size=15) p_im = p_ax.imshow(p_im.data, extent=p_im.extent) p_divider = make_axes_locatable(p_ax) p_ax_cb = p_divider.new_horizontal(size="5%", pad=0.05) p_fig = p_ax.get_figure() p_fig.add_axes(p_ax_cb) p_cb = plt.colorbar(p_im, cax=p_ax_cb) p_cb.ax.set_ylabel(r'$p$', rotation=0, labelpad=10, size=15) mu_f_ax.set_ylabel('Y (cm)') p_ax.set_xlabel('X (cm)') fig.suptitle(title) plt.show()
def test_extendednorm(): a = np.zeros((4, 5)) a[0,0] = -9999 a[1,1] = 1.1 a[2,2] = 2.2 a[2,4] = 1.9 a[3,3] = 9999999 cm = mpl.cm.get_cmap('jet') bounds = [0,1,2,3] norm = cleo.colors.ExtendedNorm(bounds, cm.N, extend='both') #fig, (ax1, ax2) = plt.subplots(1, 2) fig = plt.figure() ax1 = fig.add_subplot(1, 2, 1) ax2 = fig.add_subplot(1, 2, 2) imax = ax1.imshow(a, interpolation='None', norm=norm, cmap=cm, origin='lower'); divider = make_axes_locatable(ax1) cax = divider.append_axes("right", size="5%", pad=0.2) plt.colorbar(imax, cax=cax, extend='both') ti = cm(norm(a)) ax2.imshow(ti, interpolation='None', origin='lower') divider = make_axes_locatable(ax2) cax = divider.append_axes("right", size="5%", pad=0.2) cbar = mpl.colorbar.ColorbarBase(cax, extend='both', cmap=cm, norm=norm) fig.tight_layout()
def compare_to_model(srcs, img, fig=None, axarr=None): """ plots true image, model image, and difference (much like above) Input: srcs: python list of PointSrcParams img : FitsImage object Output: fig, axarr """ if fig is None or axarr is None: fig, axarr = plt.subplots(1, 3) # generate model image model_img = gen_model_image(srcs, img) vmin = min(img.nelec.min(), model_img.min()) vmax = max(img.nelec.max(), model_img.max()) im1 = axarr[0].imshow(np.log(img.nelec), interpolation='none', origin='lower', vmin=np.log(vmin), vmax=np.log(vmax)) axarr[0].set_title('log data ($\log(x_{n,m})$') im2 = axarr[1].imshow(np.log(model_img), interpolation='none', origin='lower', vmin=np.log(vmin), vmax=np.log(vmax)) axarr[1].set_title('log model ($\log(F_{n,m})$)') divider2 = make_axes_locatable(axarr[1]) cax2 = divider2.append_axes('right', size='10%', pad=.05) cbar2 = fig.colorbar(im2, cax=cax2) im3 = axarr[2].imshow(img.nelec-model_img, interpolation='none', origin='lower') axarr[2].set_title('Difference: Data - Model') divider3 = make_axes_locatable(axarr[2]) cax3 = divider3.append_axes('right', size='10%', pad=.05) cbar3 = fig.colorbar(im3, cax=cax3) return fig, axarr
def createColorbar(patches, cMin=None, cMax=None, nLevs=5, label=None, orientation='horizontal', *args, **kwargs): cbarTarget = plt cax = None divider = None #if hasattr(patches, 'figure'): #cbarTarget = patches.figure #print( patches) if hasattr(patches, 'ax'): divider = make_axes_locatable(patches.ax) elif hasattr(patches, 'get_axes'): divider = make_axes_locatable(patches.get_axes()) if divider: if orientation == 'horizontal': cax = divider.append_axes("bottom", size=0.25, pad=0.65) else: cax = divider.append_axes("right", size=0.25, pad=0.05) #cax = divider.append_axes("right", size="5%", pad=0.05) #cbar3 = plt.colorbar(im3, cax=cax3) #print(patches, cax) cbar = cbarTarget.colorbar(patches, cax=cax, orientation=orientation) setCbarLevels(cbar, cMin, cMax, nLevs) if label is not None: cbar.set_label(label) return cbar
def plotarray(zonearray,Z,dirname,runid): """ Plots HY properties """ assert(len(Z.shape)==2) assert(len(zonearray.shape)==2) fig =plt.figure(figsize=(11,8.5)) fig.subplots_adjust(hspace=0.45, wspace=0.3) """Compute the log of HY """ nrows,ncols=Z.shape logZ =np.log10(Z) logZ1d=np.reshape(logZ, (nrows*ncols,)) """Histogram of log HY """ ax3=fig.add_subplot(2,1,1) mybins=np.arange(-3.0,4.0,0.333333) ax3.hist(logZ1d, bins=mybins, normed=0, facecolor='green', alpha=0.75) ax3.set_xlabel('Log10 HY') ax3.set_ylabel('Frequency') ax3.set_ylim(0,30000) ax3.grid(True) """Plot of HY Zone Array """ ax1=fig.add_subplot(2,2,3) im1 =ax1.imshow(zonearray,interpolation='bilinear') """ create an axes on the right side of ax1. The width of cax will be 5% of ax and the padding between cax1 and ax1 will be fixed at 0.05 inch. """ divider= make_axes_locatable(ax1) cax1=divider.append_axes("right",size="5%",pad=0.05) cbar1=plt.colorbar(im1, cax=cax1,ticks=[0,1]) cbar1.ax.set_yticklabels(['Low','High']) #Vertically Oriented Colorbar ax1.set_title('HYZones'+"{0:04d}".format(runid)) """Plot of HY Array""" ax =fig.add_subplot(2,2,4) im =ax.imshow(logZ,interpolation='bilinear',vmin=-2,vmax=2) """ create an axes on the right side of ax. The width of cax will be 5% of ax and the padding between cax and ax will be fixed at 0.05 inch. """ divider= make_axes_locatable(ax) cax=divider.append_axes("right",size="5%",pad=0.05) #Add colorbar, make sure to specify tick locations to match desired ticklabels cbar=plt.colorbar(im, cax=cax,ticks=[-2,-1,0,1,2]) cbar.ax.set_yticklabels(['0.01','0.1','1','10','>100']) #Vertically Oriented Colorbar ax.set_title('HYField'+"{0:04d}".format(runid)) """Save the figure """ fout =dirname +"/HY" + "{0:04d}".format(runid)+".png" plt.tight_layout() plt.savefig(fout) plt.clf()
def run(plotIt=True): """ PF: Magnetics: Analytics ======================== Comparing the magnetics field in Vancouver to Seoul """ xr = np.linspace(-300, 300, 41) yr = np.linspace(-300, 300, 41) X, Y = np.meshgrid(xr, yr) Z = np.ones((np.size(xr), np.size(yr)))*150 # Bz component in Korea inckr = -8. + 3./60 deckr = 54. + 9./60 btotkr = 50898.6 Bokr = PF.MagAnalytics.IDTtoxyz(inckr, deckr, btotkr) bx, by, bz = PF.MagAnalytics.MagSphereAnaFunA( X, Y, Z, 100., 0., 0., 0., 0.01, Bokr, 'secondary' ) Bzkr = np.reshape(bz, (np.size(xr), np.size(yr)), order='F') # Bz component in Canada incca = 16. + 49./60 decca = 70. + 19./60 btotca = 54692.1 Boca = PF.MagAnalytics.IDTtoxyz(incca, decca, btotca) bx, by, bz = PF.MagAnalytics.MagSphereAnaFunA( X, Y, Z, 100., 0., 0., 0., 0.01, Boca, 'secondary' ) Bzca = np.reshape(bz, (np.size(xr), np.size(yr)), order='F') if plotIt: import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable fig = plt.figure(figsize=(14, 5)) ax1 = plt.subplot(121) dat1 = plt.imshow(Bzkr, extent=[min(xr), max(xr), min(yr), max(yr)]) divider = make_axes_locatable(ax1) cax1 = divider.append_axes("right", size="5%", pad=0.05) ax1.set_xlabel('East-West (m)') ax1.set_ylabel('South-North (m)') plt.colorbar(dat1, cax=cax1) ax1.set_title('$B_z$ field at Seoul, South Korea') ax2 = plt.subplot(122) dat2 = plt.imshow(Bzca, extent=[min(xr), max(xr), min(yr), max(yr)]) divider = make_axes_locatable(ax2) cax2 = divider.append_axes("right", size="5%", pad=0.05) ax2.set_xlabel('East-West (m)') ax2.set_ylabel('South-North (m)') plt.colorbar(dat2, cax=cax2) ax2.set_title('$B_z$ field at Vancouver, Canada') plt.show()
def plot_class(dist_m, shape_port, dat_port, dat_star, dat_class, ft, humfile, sonpath, base, p): if len(shape_port)>2: Zdist = dist_m[shape_port[-1]*p:shape_port[-1]*(p+1)] extent = shape_port[1] else: Zdist = dist_m extent = shape_port[0] print("Plotting ... ") # create fig 1 fig = plt.figure() fig.subplots_adjust(wspace = 0, hspace=0.075) plt.subplot(2,1,1) ax = plt.gca() im = ax.imshow(np.vstack((np.flipud(dat_port),dat_star)),cmap='gray', extent=[min(Zdist), max(Zdist), -extent*(1/ft), extent*(1/ft)],origin='upper') plt.ylabel('Horizontal distance (m)'); plt.axis('tight') plt.tick_params(\ axis='x', # changes apply to the x-axis which='both', # both major and minor ticks are affected bottom='off', # ticks along the bottom edge are off labelbottom='off') # labels along the bottom edge are off try: divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) plt.colorbar(im, cax=cax) except: plt.colorbar() plt.subplot(2,1,2) ax = plt.gca() plt.imshow(np.vstack((np.flipud(dat_port), dat_star)),cmap='gray', extent=[min(Zdist), max(Zdist), -extent*(1/ft), extent*(1/ft)],origin='upper') im = ax.imshow(dat_class, alpha=0.5,extent=[min(Zdist), max(Zdist), -extent*(1/ft), extent*(1/ft)], origin='upper', cmap='YlOrRd', vmin=0, vmax=3) plt.ylabel('Horizontal distance (m)'); plt.xlabel('Distance along track (m)') plt.axis('tight') try: divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) plt.colorbar(im, cax=cax, extend='max') except: plt.colorbar(extend='max') if len(shape_port)>2: custom_save(sonpath,base+'class'+str(p)) else: custom_save(sonpath,base+'class') del fig
def plot_surface(self, save_name=None, show_bicoh=True, cmap='viridis', contour_color='k'): ''' Plot the bispectrum amplitude and (optionally) the bicoherence. Parameters ---------- save_name : str, optional Save name for the figure. Enables saving the plot. show_bicoh : bool, optional Plot the bicoherence surface. Enabled by default. cmap : {str, matplotlib color map}, optional Colormap to use in the plots. Default is viridis. contour_color : {str, RGB tuple}, optional Color of the amplitude contours. ''' import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable if show_bicoh: ax1 = plt.subplot(1, 2, 1) else: ax1 = plt.subplot(1, 1, 1) im1 = ax1.imshow(self.bispectrum_logamp, origin="lower", interpolation="nearest", cmap=cmap) divider = make_axes_locatable(ax1) cax = divider.append_axes("right", size="5%", pad=0.05) cbar1 = plt.colorbar(im1, cax=cax) cbar1.set_label(r"log$_{10}$ Bispectrum Amplitude") ax1.contour(self.bispectrum_logamp, colors=contour_color) ax1.set_xlabel(r"$k_1$") ax1.set_ylabel(r"$k_2$") if show_bicoh: ax2 = plt.subplot(1, 2, 2) im2 = ax2.imshow(self.bicoherence, origin="lower", interpolation="nearest", cmap=cmap) divider = make_axes_locatable(ax2) cax2 = divider.append_axes("right", size="5%", pad=0.05) cbar2 = plt.colorbar(im2, cax=cax2) cbar2.set_label("Bicoherence") ax2.set_xlabel(r"$k_1$") ax2.set_ylabel(r"$k_2$") plt.tight_layout() if save_name is not None: plt.savefig(save_name) plt.close() else: plt.show()
def make_axr(ax, overlaycolor='darkred', size='23%'): axr = ax.twinx() div = make_axes_locatable(axr) div.append_axes('right', size=size, add_to_figure=False) ax.spines['right'].set_color(overlaycolor) axr.tick_params(axis='y', colors=overlaycolor) axr.yaxis.label.set_color(overlaycolor) axr.yaxis.get_offset_text().set_color(overlaycolor) div = make_axes_locatable(ax) div.append_axes('right', size=size, add_to_figure=False) return axr
def __init__(self, current_surf_dem, glacier_mask, bed_dem, date, \ output_trace_files, temp_files_path, glacier_thickness_threshold): self.output_trace_files = output_trace_files self.temp_files_path = temp_files_path self.glacier_thickness_threshold = glacier_thickness_threshold self.fig = plt.figure(figsize=(16,12)) self.surf_dem_plot_title = 'Surface DEM ' + date self.sub1 = self.fig.add_subplot(131) self.sub1.set_title(self.surf_dem_plot_title) self.sub1.set_xticks([]) self.sub1.set_yticks([]) self.sub1.get_axes().set_frame_on(True) self.img1 = self.sub1.imshow(current_surf_dem) self.sub1.invert_yaxis() # makes North up self.divider1 = make_axes_locatable(plt.gca()) self.cax1 = self.divider1.append_axes("right", size="5%", pad=0.05) plt.colorbar(self.img1, cax=self.cax1) self.glacier_mask_plot_title = 'Glacier Mask ' + date self.sub2 = self.fig.add_subplot(132) self.sub2.set_title(self.glacier_mask_plot_title) self.sub2.set_xticks([]) self.sub2.set_yticks([]) self.sub2.get_axes().set_frame_on(True) self.img2 = self.sub2.imshow(glacier_mask) self.sub2.invert_yaxis() self.divider2 = make_axes_locatable(plt.gca()) self.cax2 = self.divider2.append_axes("right", size="5%", pad=0.05) plt.colorbar(self.img2, cax=self.cax2) self.glacier_thickness_plot_title = 'Glacier Thickness ' + date self.sub3 = self.fig.add_subplot(133) self.sub3.set_title(self.glacier_thickness_plot_title) self.sub3.set_xticks([]) self.sub3.set_yticks([]) self.sub3.get_axes().set_frame_on(True) self.img3 = self.sub3.imshow( \ current_surf_dem - glacier_thickness_threshold - bed_dem) self.sub3.invert_yaxis() self.divider3 = make_axes_locatable(plt.gca()) self.cax3 = self.divider3.append_axes("right", size="5%", pad=0.05) plt.colorbar(self.img3, cax=self.cax3) self.fig.tight_layout() plt.show(block=False) if self.output_trace_files: self.fig.savefig(temp_files_path + 'dem_+_glacier_mask_+_thickness_' + \ date, dpi=self.fig.dpi)
def createColorBar(gci, orientation='horizontal', size=0.2, pad=None, **kwargs): """Create a Colorbar. Shortcut to create a matplotlib colorbar within the ax for a given patchset. Parameters ---------- gci : matplotlib graphical instance orientation : string size : float pad : float **kwargs : Forwarded to updateColorBar """ cbarTarget = plt cax = None divider = None # if hasattr(patches, 'figure'): # cbarTarget = patches.figure if hasattr(gci, 'ax'): divider = make_axes_locatable(gci.ax) if hasattr(gci, 'axes'): divider = make_axes_locatable(gci.axes) elif hasattr(gci, 'get_axes'): divider = make_axes_locatable(gci.get_axes()) if divider: if orientation == 'horizontal': if pad is None: pad = 0.5 cax = divider.append_axes("bottom", size=size, pad=pad) else: if pad is None: pad = 0.1 cax = divider.append_axes("right", size=size, pad=pad) cbar = cbarTarget.colorbar(gci, cax=cax, orientation=orientation) updateColorBar(cbar, **kwargs) return cbar
def plotStressStrainFibSet(fiberSet,title,fileName=None,nContours=100,pointSize=50, fiberShape='o'): '''Represents graphically the cross-section current stresses and strains. The graphics are generated by a triangulation from the x,y coordinates of the fibers. :param fiberSet: set of fibers to be represented :param title: general title for the graphic :param fileName: name of the graphic file (defaults to None: no file generated) :param nContours: number of contours to be generated (defaults to 100). If nContours=0 or nContours=None, then each fiber is represented by a makred. :param pointSize: size of the circles to represent each of the fibers in the set in the case that nContours=0 or nContours=None (defaults to 50) :param fiberShape: marker to represent each fiber, in case nContours = 0 or None.e.g.: "o"->circle, "s"->square, "p"->pentagon (defaults to circle) ''' lsYcoo=list() lsZcoo=list() lsStrain=list() lsStress=list() for f in fiberSet: fpos=f.getPos() lsYcoo.append(fpos.x) lsZcoo.append(fpos.y) lsStrain.append(f.getStrain()) lsStress.append(f.getForce()/f.getArea()/1e6) fig,(ax1,ax2) = plt.subplots(1,2, sharex=True, sharey=True) fig.suptitle(title, fontsize=20) ax1.set_title('Strain') if nContours in [None,0]: im1=ax1.scatter(lsYcoo,lsZcoo,s=pointSize,c=lsStrain,marker=fiberShape) im2=ax2.scatter(lsYcoo,lsZcoo,s=pointSize,c=lsStress,marker=fiberShape) else: im1=ax1.tricontourf(lsYcoo,lsZcoo,lsStrain, nContours) im2=ax2.tricontourf(lsYcoo,lsZcoo,lsStress, nContours) divider1 = make_axes_locatable(ax1) cax1 = divider1.append_axes("right", size="20%", pad=0.05) cbar1 = plt.colorbar(im1,cax=cax1) ax2.set_title('Stress') # im2=ax2.tricontourf(lsYcoo,lsZcoo,lsStress, nContours) # im2=ax2.scatter(lsYcoo,lsZcoo,50,lsStress) divider2 = make_axes_locatable(ax2) cax2 = divider2.append_axes("right", size="20%", pad=0.05) cbar2 = plt.colorbar(im2,cax=cax2) if fileName<>None: plt.savefig(fileName) plt.show() return
def plot_FG_border(x1raw, y1raw, x2raw, y2raw, img1, hws_n1 = 35, hws_n2_range = [20, 125]): # plot x2GridFSim, y2GridFSim and border-grid hws_n1 = 35; hws_n2_range = [20, 125] # fitler outlier gpi = lstsq_filter(x1raw,y1raw,x2raw,y2raw, 100) print len(gpi), len(gpi[gpi]) x1 = x1raw[gpi] y1 = y1raw[gpi] x2 = x2raw[gpi] y2 = y2raw[gpi] # initial drift inter-/extrapolation x2GridFSim, y2GridFSim = get_GridFSim(x1, y1, x2, y2, img1) # get border_grid border_grid = get_border_grid(x1, y1, img1, hws_n2_range) plt.figure(num=1, figsize=(14, 6), dpi=80, facecolor='w', edgecolor='k') plt.subplot(1,3,1) ax = plt.gca() #im = ax.imshow(np.arange(100).reshape((10,10))) im = plt.imshow(x2GridFSim)#;plt.colorbar(orientation='horizontal') plt.axis('off') # create an axes on the right side of ax. The width of cax will be 5% # of ax and the padding between cax and ax will be fixed at 0.05 inch. divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) plt.colorbar(im, cax=cax) plt.subplot(1,3,2) ax = plt.gca() #im = ax.imshow(np.arange(100).reshape((10,10))) im = plt.imshow(y2GridFSim)#;plt.colorbar(orientation='horizontal') plt.axis('off') # create an axes on the right side of ax. The width of cax will be 5% # of ax and the padding between cax and ax will be fixed at 0.05 inch. divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) plt.colorbar(im, cax=cax) plt.subplot(1,3,3) ax = plt.gca() #im = ax.imshow(np.arange(100).reshape((10,10))) im = plt.imshow(border_grid)#;plt.colorbar(orientation='horizontal') plt.axis('off') # create an axes on the right side of ax. The width of cax will be 5% # of ax and the padding between cax and ax will be fixed at 0.05 inch. divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) plt.colorbar(im, cax=cax) return plt
def _plot_loading(loadings, idx, axes_manager, ax=None, comp_label='PC', no_nans=True, calibrate=True, cmap=plt.cm.gray): if ax is None: ax = plt.gca() if no_nans: loadings = np.nan_to_num(loadings) if axes_manager.navigation_dimension == 2: extent = None # get calibration from a passed axes_manager shape = axes_manager._navigation_shape_in_array if calibrate: extent = (axes_manager._axes[0].low_value, axes_manager._axes[0].high_value, axes_manager._axes[1].high_value, axes_manager._axes[1].low_value) im = ax.imshow(loadings[idx].reshape(shape), cmap=cmap, extent=extent, interpolation='nearest') div = make_axes_locatable(ax) cax = div.append_axes("right", size="5%", pad=0.05) plt.colorbar(im, cax=cax) elif axes_manager.navigation_dimension == 1: if calibrate: x = axes_manager._axes[0].axis else: x = np.arange(axes_manager._axes[0].size) ax.step(x, loadings[idx]) else: messages.warning_exit('View not supported')
def regional_subplot(lons, lats, data, extreme, cent_lat, cent_lon, min_lon, max_lon, min_lat, max_lat, parallels, meridians, cmap, vmin, title, plot_number, coastline_color, background_color): ax = plt.subplot(plot_number) ax.set_axis_bgcolor(background_color) ETA_m = haversine_distance((min_lat, cent_lon), (max_lat, cent_lon), True) XI_m = haversine_distance((min_lat, min_lon), (max_lat, max_lon),True) map = Basemap(height=ETA_m, width=XI_m, resolution='l', area_thresh=1000., projection='omerc', \ lon_0=cent_lon, lat_0=cent_lat, lon_2=cent_lon, lat_2=min_lat, lon_1=cent_lon, lat_1=max_lat) map.drawcoastlines(color=coastline_color) # labels = [left,right,top,bottom] map.drawparallels(parallels, labels=[True, False, False, False]) map.drawmeridians(meridians, labels=[False, False, False, True]) cs = map.contourf(lons, lats, data, levels=numpy.linspace((-1 * extreme), extreme, 101), cmap=cmap, vmin=vmin, vmax=extreme, extend='both', latlon=True) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="2%", pad=0.05) plt.colorbar(cs, cax=cax, ticks=[-1 * extreme, 0, extreme], extend='both') ax.set_title(title) return ax
def plot_fft(spectrum, title, dry = False, custom = None): ''' Plots a spectrogram as obtained in the above function. These conventions are mostly lifted straight from the matplotlib api. ''' n_bins, n_windows = spectrum.shape x_axis = np.linspace(0, (n_bins - 1) * n_windows / 44100., n_windows) y_axis = np.linspace(0, 22050., n_bins) X, Y = np.meshgrid(x_axis, y_axis) plt.close('all') plt.figure(figsize = (20, 13)) ax = plt.gca() ax.set_yscale('symlog') im = ax.pcolormesh(X, Y, spectrum, cmap = inferno) plt.title(title) plt.xlim(0, x_axis.max()) plt.ylim(y_axis[1], 22050) plt.xlabel('Time (seconds)') plt.ylabel('Frequency (Hz)') plt.tick_params(axis='y', which='minor') divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) plt.colorbar(im, cax=cax, ticks = np.arange(0, -140, -20), label = 'Power (dB)') plt.savefig('../Web_Interface/output/spectra/' + title + '.png') if not custom is None: if dry == True: plt.savefig('../Web_Interface/static/temp_dry.png') else: plt.savefig('../Web_Interface/static/temp_wet.png') else: plt.savefig(custom)
def save(self, name, log=False, vrange=None): if self.imdict['X'].sum() == 0.0 and log: warn("can't plot {}, in log mode".format(name), RuntimeWarning, stacklevel=2) return fig = Figure(figsize=(8,6)) canvas = FigureCanvas(fig) ax = fig.add_subplot(1,1,1) divider = make_axes_locatable(ax) cax = divider.append_axes("right", "5%", pad="1.5%") if log: norm=LogNorm() else: norm=Normalize() if vrange: self.imdict['vmin'], self.imdict['vmax'] = vrange im = ax.imshow(norm=norm,**self.imdict) cb_dict = {'cax':cax} if log: cb_dict['ticks'] = LogLocator(10, np.arange(0.1,1,0.1)) cb_dict['format'] = LogFormatterMathtext(10) try: cb = plt.colorbar(im, **cb_dict) except ValueError: print self.imdict['X'].sum() raise ax.set_xlabel(self.x_label, x=0.98, ha='right') ax.set_ylabel(self.y_label, y=0.98, ha='right') if self.cb_label: cb.set_label(self.cb_label, y=0.98, ha='right') canvas.print_figure(name, bbox_inches='tight')
def draw_ctag_rejrej(in_file, out_dir, ext='.pdf'): """ Basic heatmap of efficiency vs two rejections. """ fig = Figure(figsize=_fig_size) canvas = FigureCanvas(fig) ax = fig.add_subplot(1,1,1) ds = in_file['gaia/all'] eff_array, extent = _get_arr_extent(ds) label_rejrej_axes(ax, ds) im = ax.imshow(eff_array.T, extent=extent, origin='lower', aspect='auto') ax.set_xscale('log') ax.set_yscale('log') ax.grid(which='both') # add_contour(ax,ds) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) cb = Colorbar(ax=cax, mappable=im) out_name = '{}/rejrej{}'.format(out_dir, ext) # ignore complaints about not being able to log scale images with warnings.catch_warnings(): warnings.simplefilter("ignore") canvas.print_figure(out_name, bbox_inches='tight')
def _plotResidual(xResid, yResid, xyError, nbins=50, color='RoyalBlue'): from matplotlib import pyplot from matplotlib.patches import Ellipse from mpl_toolkits.axes_grid1 import make_axes_locatable from matplotlib.patheffects import withStroke medianxy = np.median(xResid), np.median(yResid) ## Scatter plot of residuals, and circle showing dispersion pyplot.figure() axScatter = pyplot.subplot(111) pyplot.scatter(xResid, yResid, c=color) ell = Ellipse((0, 0), 2 * xyError, 2 * xyError, 0, fc=color, alpha=0.2, zorder=-1) axScatter.add_patch(ell) ## Set up histogram axes, prettify labels and such axScatter.set_aspect(1.) divider = make_axes_locatable(axScatter) axHistx = divider.append_axes("top", 1.2, pad=0.2, sharex=axScatter) axHisty = divider.append_axes("right", 1.2, pad=0.2, sharey=axScatter) axScatter.ticklabel_format(style='sci', scilimits=(-2, 2), axis='both') for tl in axHistx.get_xticklabels(): tl.set_visible(False) for tl in axHisty.get_yticklabels(): tl.set_visible(False) histRange = (-5 * xyError, 5 * xyError) axHistx.hist(xResid, bins=nbins, range=histRange, color=color) axHisty.hist(yResid, bins=nbins, range=histRange, color=color, orientation='horizontal') axScatter.axis(histRange * 2) axScatter.annotate('medians: {:.1e},{:.1e}'.format(*medianxy), xy=(0.5, 0.05), xycoords='axes fraction', ha='center', va='bottom', bbox={'boxstyle': 'round', 'fc': 'w', 'alpha': 0.8}) pyplot.show()
def __init__(self, ax=None, hist_size=0.6, pad=0.05, figsize=(15, 8)): # make a new fig/axes if needed if ax is None: self.fig = plt.figure(figsize=figsize) self.scatter_ax = fig.add_subplot(111) else: self.scatter_ax = ax self.fig = ax.figure self.divider = make_axes_locatable(self.scatter_ax) self.scatter_ax = ax if self.scatter_ax: self.fig = self.scatter_ax.figure else: self.fig = None self.top_hists = [] self.right_hists = [] self.hist_size = hist_size self.pad = pad self.xfirst_ax = None self.yfirst_ax = None # will hold histogram data self.hxs = {} self.hys = {}
def plot_kmeans(dist_m, shape_port, dat_port, dat_star, dat_kclass, ft, humfile, sonpath, base, p): Zdist = dist_m[shape_port[-1]*p:shape_port[-1]*(p+1)] extent = shape_port[1] levels = [0.5,0.75,1.25,1.5,1.75,2,3] fig = plt.figure() plt.subplot(2,1,1) ax = plt.gca() plt.imshow(np.vstack((np.flipud(dat_port), dat_star)), cmap='gray',extent=[min(Zdist), max(Zdist), -extent*(1/ft), extent*(1/ft)],origin='upper') CS = plt.contourf(np.flipud(dat_kclass), levels, alpha=0.4, extent=[min(Zdist), max(Zdist), -extent*(1/ft), extent*(1/ft)],origin='upper', cmap='YlOrRd', vmin=0.5, vmax=3) plt.ylabel('Horizontal distance (m)') plt.xlabel('Distance along track (m)') plt.axis('tight') try: divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) plt.colorbar(CS, cax=cax) except: plt.colorbar() custom_save(sonpath,base+'class_kmeans'+str(p)) del fig
def heatmap(df, edgecolors='w', cmap=mpl.cm.RdYlBu_r, log=False): width = len(df.columns)/4 height = len(df.index)/4 fig, ax = plt.subplots(figsize=(width,height)) heatmap = ax.pcolor(df, edgecolors=edgecolors, # put white lines between squares in heatmap cmap=cmap, norm=mpl.colors.LogNorm() if log else None) ax.autoscale(tight=True) # get rid of whitespace in margins of heatmap ax.set_aspect('equal') # ensure heatmap cells are square ax.xaxis.set_ticks_position('top') # put column labels at the top ax.tick_params(bottom='off', top='off', left='off', right='off') # turn off ticks plt.yticks(np.arange(len(df.index)) + 0.5, df.index) plt.xticks(np.arange(len(df.columns)) + 0.5, df.columns, rotation=90) # ugliness from http://matplotlib.org/users/tight_layout_guide.html from mpl_toolkits.axes_grid1 import make_axes_locatable divider = make_axes_locatable(ax) cax = divider.append_axes("right", "3%", pad="1%") plt.colorbar(heatmap, cax=cax)
def setup_trace_xy(ax, t, y1, y2): ax.plot(y1, y2, 'o', color='lightblue') ax.set(aspect=1, adjustable='datalim') divider = make_axes_locatable(ax) hax = divider.append_axes('bottom', size='40%', pad=0, sharex=ax) vax = divider.append_axes('left', size='40%', pad=0, sharey=ax) for ax in [hax, vax]: ax.set(xticks=[], yticks=[], adjustable='datalim') ax.figure.add_axes(hax) ax.figure.add_axes(vax) # hax.set_xlabel('Trace 1 Amplitude') # vax.set_ylabel('Trace 2 Amplitude') vax.plot(t, y2, marker='o', color='black', mfc='lightblue') tt, y2 = scipy.ndimage.zoom(t, 30), scipy.ndimage.zoom(y2, 30) vax.fill_between(tt, y2, where=y2 > 0, facecolor='black') hax.plot(y1, t, marker='o', color='black', mfc='lightblue') tt, y1 = scipy.ndimage.zoom(t, 30), scipy.ndimage.zoom(y1, 30) hax.fill_betweenx(tt, y1, where=y1 > 0, facecolor='black') hax.margins(0.05) vax.margins(0.05) return hax, vax
def test_axes_locatable_position(): fig, ax = plt.subplots() divider = make_axes_locatable(ax) cax = divider.append_axes('right', size='5%', pad='2%') fig.canvas.draw() assert np.isclose(cax.get_position(original=False).width, 0.03621495327102808)
def make_plot(show=False): # Set up figure fig = plot.figure(figsize=(7, 6), dpi=dpi) ax = fig.add_subplot(111) # Data if deproject: intensity = deprojected_intensity else: intensity = default_intensity px_scale = header['cdelt2'] * 3600 num_x = header['naxis1'] num_y = header['naxis2'] width = num_x * px_scale height = num_y * px_scale ### Plot ### x = np.linspace(-width / 2, width / 2, num_x) y = np.linspace(-height / 2, height / 2, num_x) result = ax.pcolormesh(x, y, intensity, cmap=cmap) #result.set_clim(clim[0], clim[1]) # Add Contours peak_intensity = np.max(intensity) levels = np.linspace(0.2 * peak_intensity, peak_intensity, 5) aus_alma = width / 2 ax.contour(intensity, levels, origin='lower', linewidths=2, extent=[-aus_alma, aus_alma, -aus_alma, aus_alma], colors='DarkGray') #ax.contour(intensity, levels, origin = 'lower', linewidths = 2, colors = 'DarkGray') # Add Star plot.scatter(0, 0, c="white", s=100, marker="*", zorder=100) # star # Add Beam beam_semimajor = header['bmaj'] * 3600 beam_semiminor = header['bmin'] * 3600 beam_angle = header['bpa'] - 90 # principal axes pos_x = -0.75 * box pos_y = -0.75 * box beam = patches.Ellipse(xy=(pos_x, pos_y), width=beam_semimajor, height=beam_semiminor, color='w', fill=True, angle=beam_angle) ax.add_artist(beam) # Add Name of Disk name_x = -0.85 * box name_y = 0.75 * box plot.text(name_x, name_y, header['name'], size=30, color='w', fontname="Times New Roman") # Axes plot.xlim(-box, box) plot.ylim(-box, box) plot.axes().set_aspect('equal') ax.spines['bottom'].set_color('w') ax.spines['top'].set_color('w') ax.spines['left'].set_color('w') ax.spines['right'].set_color('w') ax.tick_params(colors='white', labelcolor='black', width=2, length=10) # Annotate Axes plot.xlabel(r"$\mathrm{Relative\ R.A.\ [arcsec]}$", fontsize=fontsize) plot.ylabel(r"$\mathrm{Relative\ Dec.\ [arcsec]}$", fontsize=fontsize) # Add Colorbar (Source: http://stackoverflow.com/questions/23270445/adding-a-colorbar-to-two-subplots-with-equal-aspect-ratios) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="4%", pad=0.2) #cax = fig.add_axes([0.9, 0.1, 0.03, 0.8]) cbar = fig.colorbar(result, cax=cax) cbar.set_label(r"$\mathrm{Jy\ /\ beam}$", fontsize=fontsize, rotation=270, labelpad=25) # Save, Show, and Close if version is None: save_fn = "%s/almaImage_%s.png" % (save_directory, header['savename']) else: save_fn = "%s/v%04d_almaImage_%s.png" % (save_directory, version, header['savename']) plot.savefig(save_fn, bbox_inches='tight', dpi=dpi) if show: plot.show() plot.close(fig) # Close Figure (to avoid too many figures)
def plot_matrix(feature_matrix, plot_distances=False, center_value=None, example_label=None, feature_label=None, value_label=None, sorting_method=None, distance_metric="Euclidean", labels=None, label_kind=None, class_palette=None, feature_indices_for_plotting=None, hide_dendrogram=False, name_parts=None): figure_name = saving.build_figure_name(name_parts) n_examples, n_features = feature_matrix.shape if plot_distances: center_value = None feature_label = None value_label = "Pairwise {} distances in {} space".format( distance_metric, value_label) if not plot_distances and feature_indices_for_plotting is None: feature_indices_for_plotting = numpy.arange(n_features) if sorting_method == "labels" and labels is None: raise ValueError("No labels provided to sort after.") if labels is not None and not class_palette: raise ValueError("No class palette provided.") # Distances (if needed) distances = None if plot_distances or sorting_method == "hierarchical_clustering": distances = sklearn.metrics.pairwise_distances( feature_matrix, metric=distance_metric.lower()) # Figure initialisation figure = pyplot.figure() axis_heat_map = figure.add_subplot(1, 1, 1) left_most_axis = axis_heat_map divider = make_axes_locatable(axis_heat_map) axis_colour_map = divider.append_axes("right", size="5%", pad=0.1) axis_labels = None axis_dendrogram = None if labels is not None: axis_labels = divider.append_axes("left", size="5%", pad=0.01) left_most_axis = axis_labels if sorting_method == "hierarchical_clustering" and not hide_dendrogram: axis_dendrogram = divider.append_axes("left", size="20%", pad=0.01) left_most_axis = axis_dendrogram # Label colours if labels is not None: label_colours = [ tuple(colour) if isinstance(colour, list) else colour for colour in [class_palette[l] for l in labels] ] unique_colours = [ tuple(colour) if isinstance(colour, list) else colour for colour in class_palette.values() ] value_for_colour = { colour: i for i, colour in enumerate(unique_colours) } label_colour_matrix = numpy.array([ value_for_colour[colour] for colour in label_colours ]).reshape(n_examples, 1) label_colour_map = matplotlib.colors.ListedColormap(unique_colours) else: label_colour_matrix = None label_colour_map = None # Heat map aspect ratio if not plot_distances: square_cells = False else: square_cells = True seaborn.set(style="white") # Sorting and optional dendrogram if sorting_method == "labels": example_indices = numpy.argsort(labels) if not label_kind: label_kind = "labels" if example_label: example_label += " sorted by " + label_kind elif sorting_method == "hierarchical_clustering": linkage = scipy.cluster.hierarchy.linkage( scipy.spatial.distance.squareform(distances, checks=False), metric="average") dendrogram = seaborn.matrix.dendrogram(distances, linkage=linkage, metric=None, method="ward", axis=0, label=False, rotate=True, ax=axis_dendrogram) example_indices = dendrogram.reordered_ind if example_label: example_label += " sorted by hierarchical clustering" elif sorting_method is None: example_indices = numpy.arange(n_examples) else: raise ValueError("`sorting_method` should be either \"labels\"" " or \"hierarchical clustering\"") # Heat map of values if plot_distances: plot_values = distances[example_indices][:, example_indices] else: plot_values = feature_matrix[ example_indices][:, feature_indices_for_plotting] if scipy.sparse.issparse(plot_values): plot_values = plot_values.A colour_bar_dictionary = {} if value_label: colour_bar_dictionary["label"] = value_label seaborn.heatmap(plot_values, center=center_value, xticklabels=False, yticklabels=False, cbar=True, cbar_kws=colour_bar_dictionary, cbar_ax=axis_colour_map, square=square_cells, ax=axis_heat_map) # Colour labels if axis_labels: seaborn.heatmap(label_colour_matrix[example_indices], xticklabels=False, yticklabels=False, cbar=False, cmap=label_colour_map, ax=axis_labels) style.reset_plot_look() # Axis labels if example_label: left_most_axis.set_ylabel(example_label) if feature_label: axis_heat_map.set_xlabel(feature_label) return figure, figure_name
def wrapped( *func_args, # figure fig=self.fig, rtcf=self.rtcf, figsize=self.figsize, overridefig=self.overridefig, savefig=self.savefig, closefig=self.closefig, suptitle=self.suptitle, # axes ax=self.ax, title=self.title, xlabel=self.xlabel, ylabel=self.ylabel, zlabel=self.zlabel, unit_labels=self.unit_labels, xlim=self.xlim, ylim=self.ylim, zlim=self.zlim, invert_axis=self.invert_axis, xscale=self.xscale, yscale=self.yscale, zscale=self.zscale, aspect=self.aspect, legend=self.legend, # colorbar colorbar=self.colorbar, clabel=self.clabel, clim=self.clim, cloc=self.cloc, # sidehists sidehists=self.sidehists, shtype=self.shtype, shbins=self.shbins, shcolor=self.shcolor, shfc=self.shfc, shec=self.shec, shxdensity=self.shxdensity, shydensity=self.shydensity, shxweights=self.shxweights, shyweights=self.shyweights, sh_xsize=self.sh_xsize, sh_ysize=self.sh_ysize, # style stylesheet=self.stylesheet, tight_layout=self.tight_layout, # modifying arguments xkw=self.xkw, **func_kwargs ): r""" """ # PRE # combining dictionaries wkw = self.xkw.copy() wkw.update(xkw) # +---- figure ----+ overridefig = True if fig == "new" else overridefig fig, oldfig = _prepare_figure( fig=fig, rtcf=rtcf, figsize=figsize, **wkw ) # override currrent figure properties if overridefig: override_figure(fig, figsize=figsize, **wkw) elif figsize is not None: set_figsize(figsize, fig=fig) # set supertitle if suptitle is not None: set_suptitle(suptitle, fig=fig, **wkw) # +---- axes ----+ ax, oldax = prepare_axes( ax=ax, rtcf=rtcf, _fig=fig, _oldfig=oldfig ) # /PRE # CALL if stylesheet is not None: if isinstance(stylesheet, str): stylesheet = (stylesheet,) else: stylesheet = "default" with pyplot.style.context(stylesheet): # argspec = inspect.getfullargspec(wrapped_function) # if argspec.varkw is not None: # accepts extra kwargs # pass _res = wrapped_function(*func_args, **func_kwargs) # /CALL # POST # +---- axes ----+ if ax is not None: ax = pyplot.gca() # set title if title is not None: set_title(title, ax=ax, **wkw) ax.set_aspect(aspect) # setting axisLabels/limits/scales axisLabels( ax, x=xlabel, y=ylabel, z=zlabel, units=unit_labels, **wkw ) axisLimits(ax, x=xlim, y=ylim, z=zlim) if invert_axis is not None: invertAxis( ax, x="x" in invert_axis, y="y" in invert_axis, z="z" in invert_axis, ) axisScales(ax, x=xscale, y=yscale, z=zscale, **wkw) # Legend if legend is not False: handles, labels = ax.get_legend_handles_labels() if labels: legend = _parseoptsdict(legend) ax.legend( handles=handles, labels=labels, **legend ) # +---- colorbar ----+ if colorbar: ckw = xkw.get("colorbar", {}) if not ckw: # allowable arguments ckw = {k: xkw.get(k) for k in _cbark if k in xkw} # any specific overrides ckw.update( { _stripprefix(k, "colorbar_"): v for k, v in ckw.items() if k.startswith("colorbar_") } ) # make colorbar if cloc is None: cbar = fig.colorbar(_res, ax=ax, **ckw) elif cloc == "in": cbar = fig.colorbar(_res, cax=ax, **ckw) elif cloc == "out": cbar = fig.colorbar(_res, ax=ax, **ckw) elif isinstance(cloc, Axes): cbar = fig.colorbar(_res, ax=cloc, **ckw) else: raise TypeError("cloc wrong type") # TODO cax in arbitrary axes # elif cloc[0] == 'in & isinstance(cloc[1], mpl.axes.Axes): # cbar = fig.colorbar(return_, cax=cloc[1], **ckw) if clim is not None: cbar.set_clim(*clim) if clabel is not None: cbar.set_label(clabel) # +---- sidehists ----+ if sidehists is not False: if sidehists is True: histy_loc = "right" histx_loc = "top" # TODO, just one option else: # TODO, detect length, don't assume 2 inputs histx_loc, histy_loc = sidehists ax.set_aspect(1.0) # so same size sidehists # create new axes on the right and top of the current axes # The first argument of the new_vertical/horizontal method is # the height (width) of the axes to be created in inches. divider = make_axes_locatable(ax) axHistx = divider.append_axes( histx_loc, sh_xsize, pad=0.1, sharex=ax ) axHisty = divider.append_axes( histy_loc, sh_ysize, pad=0.1, sharey=ax ) # make some labels invisible pyplot.setp( ( axHistx.get_xticklabels() + axHisty.get_yticklabels() ), visible=False, ) if shbins is None: if isinstance(func_args[0], np.ndarray): shbins = round( 0.3 * np.sqrt(func_args[0].shape[0]) ) if isinstance(func_args[0], (list, tuple)): shbins = round( 0.3 * np.sqrt(len(func_args[0])) ) else: shbins = 30 else: pass # _xrange = func_kwargs.get('xlim', None) histx, edges, patches = axHistx.hist( func_args[0], bins=shbins, histtype=shtype, weights=shxweights, density=shxdensity, # range=_xrange, color=shcolor, fc=shfc, ec=shec, ) histy, edges, patches = axHisty.hist( func_args[1], bins=shbins, orientation="horizontal", histtype=shtype, weights=shyweights, density=shydensity, # range=sorted(ylim), color=shcolor, fc=shfc, ec=shec, ) if histy_loc == "left": axHisty.invert_xaxis() # +---- figure ----+ # tight layout if tight_layout: # True or non-empty dict # if isinstance(tight_layout, bool): # tight_layout = {} # tight_layout: dict, bool # kwargs for pyplot.tight_layout() # default: {tight_layout} # dict: tight_layout is kwargs for fig.tight_layout() # True: call tight_layout with options from xkw # False, empty dict: do not call tight_layout tightLayout(fig=fig, tlkw=tight_layout, **wkw) # saving if savefig: # T/F save_figure(savefig, fig=fig, **wkw) if closefig: pyplot.close(fig) # old figure if ( oldfig is not None ): # Returning old figure to current status pyplot.figure(oldfig.number) fig = pyplot.gcf() # old axes if oldax is not None: fig.sca(oldax) # /POST # Returning return _res
#*****************************************************************************\ row = 1 column = 4 fig, axes = plt.subplots(row, column, facecolor='w', figsize=(22,5)) ax0, ax1, ax2, ax3 = axes.flat cmap='seismic' #cmap='cool' #*****************************************************************************\ vmax=290 vmin=260 limu=vmax+5 v = np.arange(vmin, limu, 5) img1= ax0.pcolor(xi, yi, zi, cmap=cmap,vmin=vmin, vmax=vmax) div = make_axes_locatable(ax0) cax = div.append_axes("right", size="6%", pad=0.05) cbar = plt.colorbar(img1, cax=cax, format="%.0f") #cbar.ax.set_title(' height (mts.)', size=12) cbar.ax.tick_params(labelsize=14) ax0.set_title('Temperature (K) 925 hPa', size=18) ax0.set_yticks([0], minor=True) ax0.set_xticks([0], minor=True) ax0.grid(b=True, which='minor', color='k', linestyle='-',linewidth=1) ax0.grid(b=True, which='major', color='grey', linestyle='--') ax0.set_ylabel('Distance from low (deg)', size=18) ax0.set_xlabel('Distance from low (deg)', size=18) ax0.margins(0.05) #*****************************************************************************\ vmax=10 vmin=0
def _plot_surface_data(lats, lons, data, time, lat_min, lat_max, lon_min, lon_max, output_filename='noname.png', title='', units='', cm_edge_values=None, cb_tick_fmt="%.0f", cb_labels=None, cb_label_pos=None, colormap_strategy='nonlinear', cmp_name='jet', colors=None, extend='both', fill_color='1.0', plotStyle='contourf', contourLines=True, contourLabels=True, smoothFactor=1, proj=self._DEFAULT_PROJ, product_label_str=None, vlat=None, vlon=None, u=None, v=None, draw_every=1, arrow_scale=10, resolution=None, area=None, boundaryInUse='True'): d_cmap, norm = from_levels_and_colors(cm_edge_values, None, cmp_name, extend=extend) m = Basemap(projection=proj, llcrnrlat=lat_min, llcrnrlon=lon_min, urcrnrlat=lat_max, urcrnrlon=lon_max, resolution='i') # Plot data x2, y2 = m(*np.meshgrid(lons, lats)) u = data[0][time] v = data[1][time] mag = np.sqrt(u**2 + v**2) img = m.pcolormesh(x2, y2, mag, shading='flat', cmap=d_cmap, norm=norm) img.set_clim(cm_edge_values.min(), cm_edge_values.max()) #plot vectors if area == 'pac': every = 50 scale = 10 else: every = 10 scale = 10 lons = lons[::every] lats = lats[::every] x2, y2 = m(*np.meshgrid(lons, lats)) u2 = u[::every, ::every] v2 = v[::every, ::every] rad = np.arctan2(v2, u2) m.quiver(x2, y2, np.cos(rad), np.sin(rad), scale=scale, zorder=3, scale_units='inches', pivot='middle') # Draw land, coastlines, parallels, meridians and add title m.drawmapboundary(linewidth=1.0, fill_color=fill_color) m.drawcoastlines(linewidth=0.5, color='#505050', zorder=8) m.fillcontinents(color='0.58', zorder=7) parallels, p_dec_places = get_tick_values(lat_min, lat_max) meridians, m_dec_places = get_tick_values(lon_min, lon_max) m.drawparallels(parallels, labels=[True, False, False, False], fmt='%.' + str(p_dec_places) + 'f', fontsize=6, dashes=[3, 3], color='gray') m.drawmeridians(meridians, labels=[False, False, False, True], fmt='%.' + str(m_dec_places) + 'f', fontsize=6, dashes=[3, 3], color='gray') plt.title(title, fontsize=9) # Draw colorbar ax = plt.gca() divider = make_axes_locatable(ax) cax = divider.append_axes("right", size=0.2, pad=0.3) if cb_label_pos is None: tick_pos = cm_edge_values else: tick_pos = cb_label_pos if boundaryInUse == 'True': cb = plt.colorbar( img, cax=cax, # spacing='proportional', spacing='uniform', drawedges='False', orientation='vertical', extend=extend, ticks=tick_pos, boundaries=cm_edge_values) else: cb = plt.colorbar(img, cax=cax, spacing='uniform', drawedges='False', orientation='vertical', extend=extend, ticks=tick_pos) if cb_labels is None: cb.set_ticklabels([cb_tick_fmt % k for k in cm_edge_values]) else: cb.set_ticklabels(cb_labels) for tick in cb.ax.get_yticklabels(): tick.set_fontsize(7) cb.set_label(units, fontsize=8) # Patch for graphics bug that affects label positions for # long/narrow plots lat_extent = np.float(lat_max) - np.float(lat_min) lon_extent = np.float(lon_max) - np.float(lon_min) aspect_ratio = abs(lon_extent / lat_extent) if aspect_ratio > 1.7: copyright_label_yadj = -0.25 else: copyright_label_yadj = -0.10 if aspect_ratio < 0.7: copyright_label_xadj = -0.2 product_label_xadj = 1.4 else: copyright_label_xadj = -0.1 product_label_xadj = 1.04 # Draw copyright and product labels box = TextArea(getCopyright(), textprops=dict(color='k', fontsize=6)) copyrightBox = AnchoredOffsetbox( loc=3, child=box, borderpad=0.1, bbox_to_anchor=(copyright_label_xadj, copyright_label_yadj), frameon=False, bbox_transform=ax.transAxes) ax.add_artist(copyrightBox) if product_label_str is not None: box = TextArea(product_label_str, textprops=dict(color='k', fontsize=6)) copyrightBox = AnchoredOffsetbox( loc=4, child=box, borderpad=0.1, bbox_to_anchor=(product_label_xadj, copyright_label_yadj), frameon=False, bbox_transform=ax.transAxes) ax.add_artist(copyrightBox) # Save figure plt.savefig(output_filename, dpi=150, bbox_inches='tight', pad_inches=0.6) plt.close() pngcrush(output_filename)
def makeSlitIllum(self, adinputs=None, **params): """ Makes the processed Slit Illumination Function by binning a 2D spectrum along the dispersion direction, fitting a smooth function for each bin, fitting a smooth 2D model, and reconstructing the 2D array using this last model. Its implementation based on the IRAF's `noao.twodspec.longslit.illumination` task following the algorithm described in [Valdes, 1968]. It expects an input calibration image to be an a dispersed image of the slit without illumination problems (e.g, twilight flat). The spectra is not required to be smooth in wavelength and may contain strong emission and absorption lines. The image should contain a `.mask` attribute in each extension, and it is expected to be overscan and bias corrected. Parameters ---------- adinputs : list List of AstroData objects containing the dispersed image of the slit of a source free of illumination problems. The data needs to have been overscan and bias corrected and is expected to have a Data Quality mask. bins : {None, int}, optional Total number of bins across the dispersion axis. If None, the number of bins will match the number of extensions on each input AstroData object. It it is an int, it will create N bins with the same size. border : int, optional Border size that is added on every edge of the slit illumination image before cutting it down to the input AstroData frame. smooth_order : int, optional Order of the spline that is used in each bin fitting to smooth the data (Default: 3) x_order : int, optional Order of the x-component in the Chebyshev2D model used to reconstruct the 2D data from the binned data. y_order : int, optional Order of the y-component in the Chebyshev2D model used to reconstruct the 2D data from the binned data. Return ------ List of AstroData : containing an AstroData with the Slit Illumination Response Function for each of the input object. References ---------- .. [Valdes, 1968] Francisco Valdes "Reduction Of Long Slit Spectra With IRAF", Proc. SPIE 0627, Instrumentation in Astronomy VI, (13 October 1986); https://doi.org/10.1117/12.968155 """ log = self.log log.debug(gt.log_message("primitive", self.myself(), "starting")) timestamp_key = self.timestamp_keys[self.myself()] suffix = params["suffix"] bins = params["bins"] border = params["border"] debug_plot = params["debug_plot"] smooth_order = params["smooth_order"] cheb2d_x_order = params["x_order"] cheb2d_y_order = params["y_order"] ad_outputs = [] for ad in adinputs: if len(ad) > 1 and "mosaic" not in ad[0].wcs.available_frames: log.info('Add "mosaic" gWCS frame to input data') geotable = import_module('.geometry_conf', self.inst_lookups) # deepcopy prevents modifying input `ad` inplace ad = transform.add_mosaic_wcs(deepcopy(ad), geotable) log.info("Temporarily mosaicking multi-extension file") mosaicked_ad = transform.resample_from_wcs( ad, "mosaic", attributes=None, order=1, process_objcat=False) else: log.info('Input data already has one extension and has a ' '"mosaic" frame.') # deepcopy prevents modifying input `ad` inplace mosaicked_ad = deepcopy(ad) log.info("Transposing data if needed") dispaxis = 2 - mosaicked_ad[0].dispersion_axis() # python sense should_transpose = dispaxis == 1 data, mask, variance = _transpose_if_needed( mosaicked_ad[0].data, mosaicked_ad[0].mask, mosaicked_ad[0].variance, transpose=should_transpose) log.info("Masking data") data = np.ma.masked_array(data, mask=mask) variance = np.ma.masked_array(variance, mask=mask) std = np.sqrt(variance) # Easier to work with log.info("Creating bins for data and variance") height = data.shape[0] width = data.shape[1] if bins is None: nbins = max(len(ad), 12) bin_limits = np.linspace(0, height, nbins + 1, dtype=int) elif isinstance(bins, int): nbins = bins bin_limits = np.linspace(0, height, nbins + 1, dtype=int) else: # ToDo: Handle input bins as array raise TypeError("Expected None or Int for `bins`. " "Found: {}".format(type(bins))) bin_top = bin_limits[1:] bin_bot = bin_limits[:-1] binned_data = np.zeros_like(data) binned_std = np.zeros_like(std) log.info("Smooth binned data and variance, and normalize them by " "smoothed central value") for bin_idx, (b0, b1) in enumerate(zip(bin_bot, bin_top)): rows = np.arange(width) avg_data = np.ma.mean(data[b0:b1], axis=0) model_1d_data = astromodels.UnivariateSplineWithOutlierRemoval( rows, avg_data, order=smooth_order) avg_std = np.ma.mean(std[b0:b1], axis=0) model_1d_std = astromodels.UnivariateSplineWithOutlierRemoval( rows, avg_std, order=smooth_order) slit_central_value = model_1d_data(rows)[width // 2] binned_data[b0:b1] = model_1d_data(rows) / slit_central_value binned_std[b0:b1] = model_1d_std(rows) / slit_central_value log.info("Reconstruct 2D mosaicked data") bin_center = np.array(0.5 * (bin_bot + bin_top), dtype=int) cols_fit, rows_fit = np.meshgrid(np.arange(width), bin_center) fitter = fitting.SLSQPLSQFitter() model_2d_init = models.Chebyshev2D(x_degree=cheb2d_x_order, x_domain=(0, width), y_degree=cheb2d_y_order, y_domain=(0, height)) model_2d_data = fitter(model_2d_init, cols_fit, rows_fit, binned_data[rows_fit, cols_fit]) model_2d_std = fitter(model_2d_init, cols_fit, rows_fit, binned_std[rows_fit, cols_fit]) rows_val, cols_val = \ np.mgrid[-border:height+border, -border:width+border] slit_response_data = model_2d_data(cols_val, rows_val) slit_response_mask = np.pad( mask, border, mode='edge') # ToDo: any update to the mask? slit_response_std = model_2d_std(cols_val, rows_val) slit_response_var = slit_response_std**2 del cols_fit, cols_val, rows_fit, rows_val _data, _mask, _variance = _transpose_if_needed( slit_response_data, slit_response_mask, slit_response_var, transpose=dispaxis == 1) log.info("Update slit response data and data_section") slit_response_ad = deepcopy(mosaicked_ad) slit_response_ad[0].data = _data slit_response_ad[0].mask = _mask slit_response_ad[0].variance = _variance if "mosaic" in ad[0].wcs.available_frames: log.info( "Map coordinates between slit function and mosaicked data" ) # ToDo: Improve message? slit_response_ad = _split_mosaic_into_extensions( ad, slit_response_ad, border_size=border) elif len(ad) == 1: log.info("Trim out borders") slit_response_ad[0].data = \ slit_response_ad[0].data[border:-border, border:-border] slit_response_ad[0].mask = \ slit_response_ad[0].mask[border:-border, border:-border] slit_response_ad[0].variance = \ slit_response_ad[0].variance[border:-border, border:-border] log.info("Update metadata and filename") gt.mark_history(slit_response_ad, primname=self.myself(), keyword=timestamp_key) slit_response_ad.update_filename(suffix=suffix, strip=True) ad_outputs.append(slit_response_ad) # Plotting ------ if debug_plot: log.info("Creating plots") palette = copy(plt.cm.cividis) palette.set_bad('r', 0.75) norm = vis.ImageNormalize(data[~data.mask], stretch=vis.LinearStretch(), interval=vis.PercentileInterval(97)) fig = plt.figure(num="Slit Response from MEF - {}".format( ad.filename), figsize=(12, 9), dpi=110) gs = gridspec.GridSpec(nrows=2, ncols=3, figure=fig) # Display raw mosaicked data and its bins --- ax1 = fig.add_subplot(gs[0, 0]) im1 = ax1.imshow(data, cmap=palette, origin='lower', vmin=norm.vmin, vmax=norm.vmax) ax1.set_title("Mosaicked Data\n and Spectral Bins", fontsize=10) ax1.set_xlim(-1, data.shape[1]) ax1.set_xticks([]) ax1.set_ylim(-1, data.shape[0]) ax1.set_yticks(bin_center) ax1.tick_params(axis=u'both', which=u'both', length=0) ax1.set_yticklabels( ["Bin {}".format(i) for i in range(len(bin_center))], fontsize=6) _ = [ax1.spines[s].set_visible(False) for s in ax1.spines] _ = [ax1.axhline(b, c='w', lw=0.5) for b in bin_limits] divider = make_axes_locatable(ax1) cax1 = divider.append_axes("right", size="5%", pad=0.05) plt.colorbar(im1, cax=cax1) # Display non-smoothed bins --- ax2 = fig.add_subplot(gs[0, 1]) im2 = ax2.imshow(binned_data, cmap=palette, origin='lower') ax2.set_title("Binned, smoothed\n and normalized data ", fontsize=10) ax2.set_xlim(0, data.shape[1]) ax2.set_xticks([]) ax2.set_ylim(0, data.shape[0]) ax2.set_yticks(bin_center) ax2.tick_params(axis=u'both', which=u'both', length=0) ax2.set_yticklabels( ["Bin {}".format(i) for i in range(len(bin_center))], fontsize=6) _ = [ax2.spines[s].set_visible(False) for s in ax2.spines] _ = [ax2.axhline(b, c='w', lw=0.5) for b in bin_limits] divider = make_axes_locatable(ax2) cax2 = divider.append_axes("right", size="5%", pad=0.05) plt.colorbar(im2, cax=cax2) # Display reconstructed slit response --- vmin = slit_response_data.min() vmax = slit_response_data.max() ax3 = fig.add_subplot(gs[1, 0]) im3 = ax3.imshow(slit_response_data, cmap=palette, origin='lower', vmin=vmin, vmax=vmax) ax3.set_title("Reconstructed\n Slit response", fontsize=10) ax3.set_xlim(0, data.shape[1]) ax3.set_xticks([]) ax3.set_ylim(0, data.shape[0]) ax3.set_yticks([]) ax3.tick_params(axis=u'both', which=u'both', length=0) _ = [ax3.spines[s].set_visible(False) for s in ax3.spines] divider = make_axes_locatable(ax3) cax3 = divider.append_axes("right", size="5%", pad=0.05) plt.colorbar(im3, cax=cax3) # Display extensions --- ax4 = fig.add_subplot(gs[1, 1]) ax4.set_xticks([]) ax4.set_yticks([]) _ = [ax4.spines[s].set_visible(False) for s in ax4.spines] sub_gs4 = gridspec.GridSpecFromSubplotSpec(nrows=len(ad), ncols=1, subplot_spec=gs[1, 1], hspace=0.03) # The [::-1] is needed to put the fist extension in the bottom for i, ext in enumerate(slit_response_ad[::-1]): ext_data, ext_mask, ext_variance = _transpose_if_needed( ext.data, ext.mask, ext.variance, transpose=dispaxis == 1) ext_data = np.ma.masked_array(ext_data, mask=ext_mask) sub_ax = fig.add_subplot(sub_gs4[i]) im4 = sub_ax.imshow(ext_data, origin="lower", vmin=vmin, vmax=vmax, cmap=palette) sub_ax.set_xlim(0, ext_data.shape[1]) sub_ax.set_xticks([]) sub_ax.set_ylim(0, ext_data.shape[0]) sub_ax.set_yticks([ext_data.shape[0] // 2]) sub_ax.set_yticklabels( ["Ext {}".format(len(slit_response_ad) - i - 1)], fontsize=6) _ = [ sub_ax.spines[s].set_visible(False) for s in sub_ax.spines ] if i == 0: sub_ax.set_title( "Multi-extension\n Slit Response Function") divider = make_axes_locatable(ax4) cax4 = divider.append_axes("right", size="5%", pad=0.05) plt.colorbar(im4, cax=cax4) # Display Signal-To-Noise Ratio --- snr = data / np.sqrt(variance) norm = vis.ImageNormalize(snr[~snr.mask], stretch=vis.LinearStretch(), interval=vis.PercentileInterval(97)) ax5 = fig.add_subplot(gs[0, 2]) im5 = ax5.imshow(snr, cmap=palette, origin='lower', vmin=norm.vmin, vmax=norm.vmax) ax5.set_title("Mosaicked Data SNR", fontsize=10) ax5.set_xlim(-1, data.shape[1]) ax5.set_xticks([]) ax5.set_ylim(-1, data.shape[0]) ax5.set_yticks(bin_center) ax5.tick_params(axis=u'both', which=u'both', length=0) ax5.set_yticklabels( ["Bin {}".format(i) for i in range(len(bin_center))], fontsize=6) _ = [ax5.spines[s].set_visible(False) for s in ax5.spines] _ = [ax5.axhline(b, c='w', lw=0.5) for b in bin_limits] divider = make_axes_locatable(ax5) cax5 = divider.append_axes("right", size="5%", pad=0.05) plt.colorbar(im5, cax=cax5) # Display Signal-To-Noise Ratio of Slit Illumination --- slit_response_snr = np.ma.masked_array( slit_response_data / np.sqrt(slit_response_var), mask=slit_response_mask) ax6 = fig.add_subplot(gs[1, 2]) im6 = ax6.imshow(slit_response_snr, origin="lower", vmin=norm.vmin, vmax=norm.vmax, cmap=palette) ax6.set_xlim(0, slit_response_snr.shape[1]) ax6.set_xticks([]) ax6.set_ylim(0, slit_response_snr.shape[0]) ax6.set_yticks([]) ax6.set_title("Reconstructed\n Slit Response SNR") _ = [ax6.spines[s].set_visible(False) for s in ax6.spines] divider = make_axes_locatable(ax6) cax6 = divider.append_axes("right", size="5%", pad=0.05) plt.colorbar(im6, cax=cax6) # Save plots --- fig.tight_layout(rect=[0, 0, 0.95, 1], pad=0.5) fname = slit_response_ad.filename.replace(".fits", ".png") log.info("Saving plots to {}".format(fname)) plt.savefig(fname) return ad_outputs
fw.setnchannels(channels) fw.setsampwidth(bits // 8) fw.setframerate(sample_rate) fw.writeframes(data) fw.close() audio, slices = load_and_trim(path) print('Duration: %.2f s' % (audio.shape[0] / sr)) plt.figure(figsize=(12, 5)) plt.plot(np.arange(len(audio)), audio) plt.title('Raw Audio Signal') plt.xlabel('Time') plt.ylabel('Audio Amplitude') plt.show() feature = mfcc(audio, sr, numcep=mfcc_dim) print('Shape of MFCC:', feature.shape) fig = plt.figure(figsize=(12, 5)) ax = fig.add_subplot(111) im = ax.imshow(feature, cmap=plt.cm.jet, aspect='auto') plt.title('Normalized MFCC') plt.ylabel('Time') plt.xlabel('MFCC Coefficient') plt.colorbar(im, cax=make_axes_locatable(ax).append_axes('right', size='5%', pad=0.05)) ax.set_xticks(np.arange(0, 13, 2), minor=False) plt.show()
def add_cbar(im, ax): divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="10%", pad=0.05) plt.colorbar(im, cax=cax)
def huelsenbeck_svg(request): import numpy as np import tkinter import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from matplotlib.pyplot import xticks, yticks import matplotlib.cm as cm from mpl_toolkits.axes_grid1 import ImageGrid from math import log import os import tempfile plt.ioff() cmap = cm.jet reconstruction_set_id = request.matchdict['reconstruction_set_id'] # method=request.matchdict['method'] # m=request.matchdict['m'] # genes=request.matchdict['genes'] # kvd_method=request.matchdict['kvd_method'] # k=tuple(request.matchdict['k'].split("_")) reconstruction_set = DBSession.query(HuelsenbeckReconstructionSet).get( reconstruction_set_id) from sqlalchemy.orm import joinedload from sqlalchemy.orm import defaultload a_max = reconstruction_set.simulation_set.a_max b_max = reconstruction_set.simulation_set.b_max nr_rows = reconstruction_set.simulation_set.rows nr_cols = reconstruction_set.simulation_set.cols # set of arrays to store cell data n = np.zeros((nr_rows, nr_cols)) d = np.zeros((nr_rows, nr_cols)) # Method 1 # for row in range(nr_rows): # print(row) # for col in range(nr_cols): # print(col) # huelsenbeck_reconstructions = DBSession.query(HuelsenbeckReconstruction).filter(reconstruction_set==reconstruction_set).filter(row==row).filter(col==col).all() # n[row,col] = sum([huelsenbeck_reconstruction.success for huelsenbeck_reconstruction in huelsenbeck_reconstructions]) # d[row,col] = len(huelsenbeck_reconstructions) # # Name the output file # Read input data from FITS file for huelsenbeck_reconstruction in reconstruction_set.huelsenbeck_reconstructions: row = huelsenbeck_reconstruction.huelsenbeck_simulation.row col = huelsenbeck_reconstruction.huelsenbeck_simulation.col d[row, col] += 1 if bool(huelsenbeck_reconstruction.reconstruction.success): n[row, col] += 1 print(n) print(d) z = n / d print(z) # Define x and y labels x = np.linspace(0, a_max, z.shape[1]) y = np.linspace(0, b_max, z.shape[0]) # Set colomap cmap = cm.jet # Setup contour levels levels = np.arange(0, 1.1, 0.1) # Setup figure and colorbar fig = plt.figure(figsize=(6, 6)) #ax = fig.add_subplot(111) ax = fig.add_axes((.1, .3, .8, .6)) #fig = plt.figure(figsize=(6,8)) #ax = plt.add_axes((.1,.3,.8,.6)) #plt.locator_params(axis='y', tight=True, nbins=nr_rows-1) #plt.locator_params(axis='x', tight=True, nbins=nr_cols-1) #im = ax.contourf(x, y, z, levels=levels, antialiased=False, cmap=cmap) im = plt.imshow(z, origin='lower', clim=(0.0, 1.0)) ax.set_xlabel('a') ax.set_ylabel('b') avals = [(col + 1) * (a_max) / nr_cols for col in range(nr_cols)] #np.linspace(0,a_max,nr_cols) bvals = [(row + 1) * (b_max) / nr_rows for row in range(nr_rows)] #np.linspace(0,b_max,nr_rows) xticks(range(nr_cols), ["{:0.2f}".format(aval) for aval in list(avals)]) yticks(range(nr_rows), ["{:0.2f}".format(bval) for bval in list(bvals)]) #xticks(xticks()[0][1:-1], [str(t*a_max/float(nr_cols-1)) for t in xticks()[0][1:-1]]) #yticks(yticks()[0][1:-1], reversed([str(t*b_max/float(nr_rows-1)) for t in yticks()[0][1:-1]])) im.set_cmap(cmap) # create an axes on the right side of ax. The width of cax will be 5% # of ax and the padding between cax and ax will be fixed at 0.05 inch. from mpl_toolkits.axes_grid1 import make_axes_locatable divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) fig.colorbar(im, cax=cax) #here = os.path.dirname(os.path.abspath(__file__)) #fd, path = tempfile.mkstemp(suffix='.svg',dir=os.path.join(here,'static','tmp')) svg_dir = os.path.join(request.settings['static_dir'], 'tmp') print(svg_dir) fd, path = tempfile.mkstemp(suffix='.svg', dir=svg_dir) plt.savefig(path) plt.close() return HTTPFound( request.static_path( os.path.join('static', 'tmp', os.path.split(path)[1])))
def colorbar(mappable, extend='neither'): ax = mappable.axes fig = ax.figure divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) return fig.colorbar(mappable, cax=cax, extend=extend)
def plot_likelihoods_hist(likelihoods, x_grid, y_grid, y_pdf=None, x_pdf=None, x_confint=None, y_confint=None, filename=None, show=True, returnimage=False, plot_axes=('centers', 'widths'), contour_confs=None): ''' Plots a heat map of likelihoodelation values as a function of velocity width and velocity center. ''' # Import external modules import numpy as np import math from mpl_toolkits.axes_grid1 import ImageGrid import pyfits as pf import matplotlib.pyplot as plt import matplotlib from mpl_toolkits.axes_grid1 import make_axes_locatable # Set up plot aesthetics plt.clf() plt.rcdefaults() colormap = plt.cm.gist_ncar #color_cycle = [colormap(i) for i in np.linspace(0, 0.9, len(flux_list))] font_scale = 12 params = {#'backend': .pdf', 'axes.labelsize': font_scale, 'axes.titlesize': font_scale, 'text.fontsize': font_scale, 'legend.fontsize': font_scale * 3 / 4.0, 'xtick.labelsize': font_scale, 'ytick.labelsize': font_scale, 'font.weight': 500, 'axes.labelweight': 500, 'text.usetex': False, #'figure.figsize': (8, 8 * y_scaling), #'axes.color_cycle': color_cycle # colors of different plots } plt.rcParams.update(params) fig, ax_image = plt.subplots(figsize=(6,6)) # Mask NaNs image = np.ma.array(likelihoods, mask=np.isnan(likelihoods)) if plot_axes[0] == 'centers': x_extent = x_grid[0], x_grid[-1] ax_image.set_xlabel(r'Velocity Center (km/s)') x_sum_axes = (1, 2) y_pdf_label = r'Centers PDF' if plot_axes[1] == 'centers': y_extent = y_grid[0], y_grid[-1] ax_image.set_ylabel(r'Velocity Center (km/s)') y_sum_axes = (1, 2) x_pdf_label = r'Centers PDF' if plot_axes[0] == 'widths': x_extent = x_grid[0], x_grid[-1] ax_image.set_xlabel(r'Velocity Width (km/s)') x_sum_axes = (0, 2) y_pdf_label = r'Width PDF' x_limits = (0, 25) if plot_axes[1] == 'widths': y_extent = y_grid[0], y_grid[-1] ax_image.set_ylabel(r'Velocity Width (km/s)') y_sum_axes = (0, 2) x_pdf_label = r'Width PDF' if plot_axes[0] == 'dgrs': x_extent = x_grid[0], x_grid[-1] ax_image.set_xlabel(r'DGR (10$^{-20}$ cm$^2$ mag$^1$)') x_sum_axes = (0, 1) y_pdf_label = r'DGR PDF' if plot_axes[1] == 'dgrs': y_extent = y_grid[0], y_grid[-1] ax_image.set_ylabel(r'DGR (10$^{-20}$ cm$^2$ mag$^1$)') y_sum_axes = (0, 1) x_pdf_label = r'DGR PDF' y_limits = (0, 0.3) sum_axes = np.array((x_sum_axes, y_sum_axes)) sum_axis = np.argmax(np.bincount(np.ravel(sum_axes))) # Create likelihood image image = np.sum(likelihoods, axis=sum_axis) / np.sum(likelihoods) # Derive marginal distributions of both centers and widths x_sum = np.sum(likelihoods, axis=x_sum_axes) x_pdf = x_sum / np.sum(x_sum) y_sum = np.sum(likelihoods, axis=y_sum_axes) y_pdf = y_sum / np.sum(y_sum) extent = np.ravel(np.array((x_extent, y_extent))) #plt.rc('text', usetex=False) im = ax_image.imshow(image.T, interpolation='nearest', origin='lower', extent=extent, #cmap=plt.cm.gist_stern, #cmap=plt.cm.gray, cmap=plt.cm.binary, #norm=matplotlib.colors.LogNorm(), aspect='auto', ) show_pdfs = 1 if show_pdfs: divider = make_axes_locatable(ax_image) ax_pdf_x = divider.append_axes("top", 1, pad=0.1, sharex=ax_image) ax_pdf_y = divider.append_axes("right", 1, pad=0.1, sharey=ax_image) # make some labels invisible plt.setp(ax_pdf_x.get_xticklabels() + \ ax_pdf_y.get_yticklabels(), visible=False) ax_pdf_x.plot(x_grid, x_pdf, color='k', drawstyle='steps-post', linewidth=2, ) ax_pdf_y.plot(y_pdf, y_grid, color='k', drawstyle='steps-post', linewidth=2, ) #axHistx.axis["bottom"].major_ticklabels.set_visible(False) # Tick marks on the pdf? pdf_ticks = False for tl in ax_pdf_x.get_xticklabels(): tl.set_visible(False) if pdf_ticks: wmax = x_pdf.max() ticks = [0, 0.5*wmax, 1.0*wmax] tick_labels = ['{0:.1f}'.format(ticks[0]), '{0:.1f}'.format(ticks[1]), '{0:.1f}'.format(ticks[2]), ] ax_pdf_x.set_yticks(ticks) ax_pdf_x.set_yticklabels(tick_labels) else: for tl in ax_pdf_x.get_yticklabels(): tl.set_visible(False) ax_pdf_x.set_ylabel(y_pdf_label) for tl in ax_pdf_y.get_yticklabels(): tl.set_visible(False) if pdf_ticks: cmax = y_pdf.max() ticks = [0, 0.5*cmax, 1.0*cmax] tick_labels = ['{0:.1f}'.format(ticks[0]), '{0:.1f}'.format(ticks[1]), '{0:.1f}'.format(ticks[2]), ] ax_pdf_y.set_xticks(ticks) ax_pdf_y.set_xticklabels(tick_labels) else: for tl in ax_pdf_y.get_xticklabels(): tl.set_visible(False) ax_pdf_y.set_xlabel(x_pdf_label) # Show confidence limits if y_confint is not None: ax_pdf_y.axhspan(y_confint[0] - y_confint[1], y_confint[0] + y_confint[2], color='k', linewidth=1, alpha=0.2) ax_pdf_y.axhline(y_confint[0], color='k', linestyle='--', linewidth=3, alpha=1) if x_confint is not None: ax_pdf_x.axvspan(x_confint[0] - x_confint[1], x_confint[0] + x_confint[2], color='k', linewidth=1, alpha=0.2) ax_pdf_x.axvline(x_confint[0], color='k', linestyle='--', linewidth=3, alpha=1) #cb.set_clim(vmin=0.) # Write label to colorbar #cb.set_label_text(r'log L') # Plot contours if contour_confs is not None: fractions = (1.0 - np.asarray(contour_confs)) levels = (fractions * image.max()) cs = ax_image.contour(image.T, levels=levels, origin='lower', extent=extent, colors='k' ) # Define a class that forces representation of float to look a certain # way This remove trailing zero so '1.0' becomes '1' class nf(float): def __repr__(self): str = '%.1f' % (self.__float__(),) if str[-1]=='0': return '%.0f' % self.__float__() else: return '%.1f' % self.__float__() # Recast levels to new class cs.levels = [nf(val) for val in np.asarray(contour_confs)*100.0] #fmt = {} #for level, fraction in zip(cs.levels, fractions): # fmt[level] = fraction fmt = '%r %%' ax_image.clabel(cs, cs.levels, fmt=fmt, fontsize=9, inline=1) try: print 'yes' ax_image.set_xlim(x_limits) ax_image.set_ylim(y_limits) except UnboundLocalError: pass if filename is not None: plt.draw() plt.savefig(filename, bbox_inches='tight') if show: plt.draw() plt.show() if returnimage: return likelihoods
if (Mean[i] < 0): b, = plt.plot(in_Degree[i], Mean[i], 'ro', label='Inhibitory columns') axScatter.scatter(in_Degree, Mean) #axScatter.set_aspect(1.) #plt.annotate('%i' %(i),xy=(in_Degree[i],Mean[i]),fontsize=8) plt.legend([a, b], ['Excitatory columns', 'Inhibitory columns'], prop={'size': 10}) #plt.legend([a],['Excitatory columns']) #plt.legend([b],['Inhibitory columns']) plt.xlabel(r'$\mathrm{Inhibitory\ in-degree}$', fontsize=20) plt.ylabel(r'$|y_1(t)-y_2(t)|$', fontsize=20) divider = make_axes_locatable(axScatter) axHisty = divider.append_axes("right", size=1.2, pad=0.3, sharey=axScatter) #axHisty.hist(Mean, bins=40, orientation='horizontal',facecolor='green') n, bins, patches = axHisty.hist(Mean, bins=30, normed=1, orientation='horizontal', facecolor='green') axHisty.set_xlim(0, 1) # make some labels invisible plt.setp(axHisty.get_yticklabels(), visible=False) #axHisty.axis["left"].major_ticklabels.set_visible(False) for tl in axHisty.get_yticklabels(): tl.set_visible(False) axHisty.set_xticks([0, 0.5, 1]) # add a 'best fit' line
def __init__(self, parent, title, fname, runNumber=1): util.GenericView.__init__(self, parent, title) self.CreateMenuBar() self.runNumber = runNumber self.mykProfileView = None self.SetSize((900, 650)) self.SetPosition((10, 10)) self.sbgen = self.CreateStatusBar() self.sbgen.SetBackgroundColour('WHITE') txt = 'read KPCMatrix file %s' % fname self.sbgen.SetStatusText(txt) # timer affichage StatusBar self.txtsb = '' self.timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.refreshSB, self.timer) """ read kpcmat.h5 file """ self.fh5 = fname """ read profile in kpcmat.h5 """ self.baseProfile = rttov.profile.Profile() self.baseProfile = rmodel.project.OpenAProfile(self.fh5, 1) t0 = time.time() frad = h5py.File(self.fh5, 'r') h5 = frad['/'] self.kmat = rttov.kpcmatrix.Kpcmatrix() self.kmat.loadh5(h5) frad.close() t1 = time.time() txt = 'read KPCMatrix file %s : %f sec.' % (self.fh5, (t1 - t0)) self.sbgen.SetStatusText(txt) # self.kmat.kpcmatrix.display() self.sat = self.kmat.misc['SATELLITE'] self.ins = self.kmat.misc['INSTRUMENT'] self.chn = self.kmat.kpcmatrix['T'].shape[1] self.lev = self.kmat.profile['NLEVELS'] # # growth the levels < 101 # # table d'equivalence des indices self.tabilevels = np.zeros(levx, int) for l in range(0, levx): self.tabilevels[l] = round(l * self.lev / levx) self.tabP = self.kmat.profile['P'] # print 'CHANNELS/NLEVELS :',self.chn, self.lev if self.lev < levx: tabNP = np.zeros(levx) for l in range(0, levx): tabNP[l] = self.tabP[self.tabilevels[l]] self.tabP = tabNP self.tabW = self.kmat.misc['WAVENUMBERS'] self.tabY = {} """ gasplot : 0.0 not shown ? """ self.tcomm = {} self.tunit = {} self.tcbar = {} self.gasplot = [] for gas in ['T', 'Q'] + gaslist: if self.kmat.kpcmatrix[gas] is None: continue kmin = np.amin(self.kmat.kpcmatrix[gas]) kmax = np.amax(self.kmat.kpcmatrix[gas]) self.tcbar[gas] = 1 if kmin == 0.0 and kmax == 0.0: self.tcbar[gas] = 0 continue attr = '%s_ATTRIBUTE' % gas self.tcomm[gas] = self.kmat.kpcmatrix[attr]['COMMENT'] self.tunit[gas] = self.kmat.kpcmatrix[attr]['UNITS'] # print gas, attr, self.tcomm[gas],' :',kmin,'<==>',kmax if not gas == 'T' and not gas == 'Q': self.gasplot.append(gas) """ ns : number of subplots """ ns = len(self.gasplot) # print 'used gases : ', self.gasplot # # init figure # self.fig = figPlot() self.cnv = FigureCanvas(self, -1, self.fig) self.cnv.mpl_connect('motion_notify_event', self.onMMotion) self.cnv.mpl_connect('key_press_event', self.onkeypress) # # subplot width # self.barwidth = 20 self.yMax = self.lev self.xMax = self.barwidth * self.chn self.txtsb = '%s / %s' % (self.sat.replace( ' ', '').upper(), self.ins.upper()) # # matplotlib ToolBar selon nombre canaux # # # choice gas in subplot 313 # self.glabel = {} self.gasID = {} if len(self.gasplot) > 1: for ig in self.gasplot: self.gasID[ig] = wx.NewId() self.glabel[self.gasID[ig]] = ig ico = os.environ["RTTOV_GUI_PREFIX"] + '/icons/%s.png' % ig self.tlb.AddSimpleTool(self.gasID[ig], _load_bitmap(ico), ig, '') wx.EVT_TOOL(self.tlb, self.gasID[ig], self.gaschoice) self.tlb = MyCustomToolbar(self.cnv) # # toolbar : custom buttons # self.LEFTLEFT_ID = wx.NewId() self.tlb.AddSimpleTool(self.LEFTLEFT_ID, _load_bitmap('hand.xpm'), 'One screen left', '') wx.EVT_TOOL(self.tlb, self.LEFTLEFT_ID, self.onleftleft) self.LEFT_ID = wx.NewId() self.tlb.AddSimpleTool(self.LEFT_ID, _load_bitmap('stock_left.xpm'), 'left', '') wx.EVT_TOOL(self.tlb, self.LEFT_ID, self.onleft) self.RIGHT_ID = wx.NewId() self.tlb.AddSimpleTool(self.RIGHT_ID, _load_bitmap('stock_right.xpm'), 'right', '') wx.EVT_TOOL(self.tlb, self.RIGHT_ID, self.onright) self.RIGHTRIGHT_ID = wx.NewId() self.tlb.AddSimpleTool(self.RIGHTRIGHT_ID, _load_bitmap('hand.xpm'), 'One screen right', '') wx.EVT_TOOL(self.tlb, self.RIGHTRIGHT_ID, self.onrightright) self.UP_ID = wx.NewId() self.tlb.AddSimpleTool(self.UP_ID, _load_bitmap('stock_up.xpm'), 'scroll up', '') wx.EVT_TOOL(self.tlb, self.UP_ID, self.onup) self.DOWN_ID = wx.NewId() self.tlb.AddSimpleTool(self.DOWN_ID, _load_bitmap('stock_down.xpm'), 'scroll down', '') wx.EVT_TOOL(self.tlb, self.DOWN_ID, self.ondown) # # add kscale icon : K / K% # self.scalek = 0 self.tlb.Realize() # canvas and toolbar in sizer sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.tlb, 0, wx.GROW) sizer.Add(self.cnv, 1, wx.LEFT | wx.TOP | wx.GROW) self.SetSizer(sizer) self.Fit() # self.kprof = None # self.subP = {} self.cax = {} # # subplots T and Q # self.subP['T'] = self.fig.add_subplot(3, 1, 1) self.tabY['T'] = self.extract_kgas('T') img = self.subP['T'].imshow(self.tabY['T'], origin='upper') self.subP['T'].set_ylabel('P levels') divider = make_axes_locatable(self.subP['T']) self.cax['T'] = divider.append_axes("right", size="1%", pad=0.05) self.fig.colorbar(img, cax=self.cax['T']) self.subP['T'].set_xlim([0, min(self.xMax, wix)]) self.draw_plot('T', 'T', self.kmat.kpcmatrix['%s_ATTRIBUTE' % 'T']['COMMENT']) self.subP['Q'] = self.fig.add_subplot(3, 1, 2, sharex=self.subP['T'], sharey=self.subP['T']) self.tabY['Q'] = self.extract_kgas('Q') img = self.subP['Q'].imshow(self.tabY['Q'], origin='upper') self.subP['Q'].set_ylabel('P levels') divider = make_axes_locatable(self.subP['Q']) self.cax['Q'] = divider.append_axes("right", size="1%", pad=0.05) self.fig.colorbar(img, cax=self.cax['Q']) self.subP['Q'].set_xlim([0, min(self.xMax, wix)]) self.draw_plot('Q', 'Q', self.kmat.kpcmatrix['%s_ATTRIBUTE' % 'Q']['COMMENT']) # # subplot other gases if exist # if self.gasplot: for gas in self.gasplot: self.tabY[gas] = self.extract_kgas(gas) gas = self.gasplot[0] self.subP['G'] = self.fig.add_subplot(3, 1, 3, sharex=self.subP['T'], sharey=self.subP['T']) img = self.subP['G'].imshow(self.tabY[gas], origin='upper') self.subP['G'].set_ylabel('P levels') divider = make_axes_locatable(self.subP['G']) self.cax['G'] = divider.append_axes("right", size="1%", pad=0.05) self.fig.colorbar(img, cax=self.cax['G']) self.subP['G'].set_xlim([0, min(self.xMax, wix)]) self.draw_plot( 'G', gas, self.kmat.kpcmatrix['%s_ATTRIBUTE' % gas]['COMMENT']) self.fig.tight_layout() self.fig.canvas.draw()
def correlation_matrix( df_x_path, df_y_path=None, x_cols=None, y_cols=None, x_dict=None, y_dict=None, x_normalize=False, y_normalize=False, correction="fdr_bh", entries=None, er=0.05, output="pearson", save_as=None, xlabel_rotation="vertical", bp_style=True, ): """ Highly parameterized correlation matrix of variables given by the columns of one or two dataframes. Parameters ---------- df_x_path : str Path to dataframe from which to select the columns as correlation matrix variables. df_y_path : str, optional Path to second dataframe from which to select the columns as correlation matrix variables. x_cols : list, optional Exclusive list of columns from `df_x_path` to use as correlation matrix variables. y_cols : list, optional Exclusive list of columns from `df_y_path` to use as correlation matrix variables. x_dict : dict, optional Dictionary based on which to rename the correlation matrix variables derived from `df_x_path` columns. y_dict : dict, optional Dictionary based on which to rename the correlation matrix variables derived from `df_y_path` columns. x_normalize : bool, optional Whether to normalize (divide by the mean) the rows from `df_x_path`. y_normalize : bool, optional Whether to normalize (divide by the mean) the rows from `df_y_path`. correction : str, optional Values from `statsmodels.stats.multitest.multitest_methods_names` specifying which mthod to use for multiple testing correction. entries : list, optional A list of values specifying which row indices from `df_x_path` and `df_y_path` to consider for the correlation matrix. er : float, optional Error rate (can be either FWER or FDR, depending on the value of `correction`) to use for the multiple testing correction. output : {"p", "pearsonr", "p_corrected", "slope"} Which correlation metric to display on the matrix. save_as : string, optional Path of output figure. xlabel_rotation : {"vertical", int}, optional How to rotate the x-axis labels. Returns ------- dfc : pandas.DataFrame Pandas dataframe of the correlation matrix. """ if bp_style: behaviopy_style() if xlabel_rotation != "vertical": ha = "left" else: ha = "center" df = pd.read_csv(df_x_path, index_col=0) if not x_cols: x_cols = list(df.columns) if df_y_path: dfy = pd.read_csv(df_y_path, index_col=0) if not y_cols: y_cols = list(dfy.columns) df = pd.concat([df, dfy], axis=1) if entries: df = df.loc[entries] if x_normalize: df[x_cols] = df[x_cols].apply(lambda x: (x / x.mean())) if y_normalize: df[y_cols] = df[y_cols].apply(lambda x: (x / x.mean())) if output == "pearsonr": dfc = df.corr() cmap = cm.PiYG cbar_label = "Pearson's r" elif output == "slope": dfc = df.corr() * (df.std().values / df.std().values[:, np.newaxis]) cmap = cm.PiYG cbar_label = "Slope" elif output == "p": n = len(df) dfc = df.corr() dfc = dfc.applymap(lambda x: p_from_r(x, n)) cmap = cm.BuPu_r cbar_label = "p-value (uncorrected)" elif output == "p_corrected": n = len(df) dfc = df.corr() dfc = dfc.applymap(lambda x: p_from_r(x, n)) dfc_corrected = multipletests(dfc.as_matrix().flatten(), er, correction)[1].reshape(np.shape(dfc)) dfc = pd.DataFrame(dfc_corrected, dfc.index, dfc.columns) cmap = cm.BuPu_r if "fdr" in correction: cbar_label = "p-value (FDR={} corrected)".format(str(er)) else: cbar_label = "p-value (FWER={} corrected)".format(str(er)) dfc = dfc.loc[y_cols] dfc = dfc[x_cols] fig, ax = plt.subplots() if output not in ["p", "p_corrected"]: im = ax.matshow(dfc, norm=MidpointNormalize(midpoint=0.), cmap=cmap) else: im = ax.matshow(dfc, norm=MidpointNormalize(midpoint=0.05), cmap=cmap) if x_dict: plt.xticks(range(len(x_cols)), failsafe_apply_dict(x_cols, x_dict), rotation=xlabel_rotation, ha=ha) else: plt.xticks(range(len(x_cols)), x_cols, rotation=xlabel_rotation, ha=ha) if y_dict: plt.yticks(range(len(y_cols)), failsafe_apply_dict(y_cols, y_dict)) else: plt.yticks(range(len(y_cols)), y_cols) ax.grid(False) ax.tick_params(axis="both", which="both", bottom="off", top="off", length=0) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) cbar = fig.colorbar(im, cax=cax, label=cbar_label) if save_as: plt.savefig(save_as, dpi=300, transparent=True) return dfc
def plot_tiles( self, cadastre_index: int, show: bool = True, with_legend: bool = True, rgb: bool = False, ): building_tiles = self.cache.mask_tiles(cadastre_index=cadastre_index) tile_dimensions = self.cache.tile_dimensions( cadastre_index=cadastre_index, ) if rgb: background_tiles = self.cache.rgb_tiles( cadastre_index=cadastre_index, ) else: background_tiles = self.cache.lidar_tiles( cadastre_index=cadastre_index, ) background_tiles = np.array(background_tiles) fig, axes = plt.subplots( *tile_dimensions, figsize=(15, 15), sharex=True, sharey=True, squeeze=False, ) cadastre_text = axes[0][-1].annotate( f'Cadastre {cadastre_index}', xy=(0.98, 0.98), xycoords='axes fraction', size=20, ha='right', va='top', color="white", weight="bold", alpha=0.5, ) cadastre_text.set_path_effects([ patheffects.withStroke(linewidth=2, foreground='black', alpha=0.3) ], ) if not rgb: vmin, vmax = background_tiles.min(), background_tiles.max() else: vmin, vmax = None, None for (lidar_tile, building_tile), ax \ in zip(zip(background_tiles, building_tiles), axes.flatten()): lidar_image = ax.imshow( np.squeeze(lidar_tile), vmin=vmin, vmax=vmax, ) rgba_building = np.zeros(shape=(256, 256, 4)) # Set building area to be semi-transparent red rgba_building[:, :, 0] = building_tile[:, :, 0] is_building = (building_tile == 1).reshape(256, 256) rgba_building[:, :, 3][is_building] = 0.25 if rgb else 0.2 ax.imshow(rgba_building, cmap="binary") if with_legend and len(axes.flatten()) == 1 and not rgb: divider = make_axes_locatable(axes[0][0]) colorbar_ax = divider.append_axes("right", size="5%", pad=0.05) fig.colorbar( lidar_image, cax=colorbar_ax, format=FormatStrFormatter('%d m'), ) else: plt.tight_layout() if show: fig.show() else: return fig, axes
def plot_cov(cov, info, exclude=(), colorbar=True, proj=False, show_svd=True, show=True, verbose=None): """Plot Covariance data. Parameters ---------- cov : instance of Covariance The covariance matrix. info: dict Measurement info. exclude : list of string | str List of channels to exclude. If empty do not exclude any channel. If 'bads', exclude info['bads']. colorbar : bool Show colorbar or not. proj : bool Apply projections or not. show_svd : bool Plot also singular values of the noise covariance for each sensor type. We show square roots ie. standard deviations. show : bool Show figure if True. %(verbose)s Returns ------- fig_cov : instance of matplotlib.figure.Figure The covariance plot. fig_svd : instance of matplotlib.figure.Figure | None The SVD spectra plot of the covariance. See Also -------- mne.compute_rank Notes ----- For each channel type, the rank is estimated using :func:`mne.compute_rank`. .. versionchanged:: 0.19 Approximate ranks for each channel type are shown with red dashed lines. """ from ..cov import Covariance import matplotlib.pyplot as plt from matplotlib.colors import Normalize if exclude == 'bads': exclude = info['bads'] info = pick_info(info, pick_channels(info['ch_names'], cov['names'], exclude)) del exclude picks_list = \ _picks_by_type(info, meg_combined=False, ref_meg=False, exclude=()) picks_by_type = dict(picks_list) ch_names = [n for n in cov.ch_names if n in info['ch_names']] ch_idx = [cov.ch_names.index(n) for n in ch_names] info_ch_names = info['ch_names'] idx_by_type = defaultdict(list) for ch_type, sel in picks_by_type.items(): idx_by_type[ch_type] = [ch_names.index(info_ch_names[c]) for c in sel if info_ch_names[c] in ch_names] idx_names = [(idx_by_type[key], '%s covariance' % DEFAULTS['titles'][key], DEFAULTS['units'][key], DEFAULTS['scalings'][key], key) for key in _DATA_CH_TYPES_SPLIT if len(idx_by_type[key]) > 0] C = cov.data[ch_idx][:, ch_idx] projs = [] if proj: projs = copy.deepcopy(info['projs']) # Activate the projection items for p in projs: p['active'] = True P, ncomp, _ = make_projector(projs, ch_names) if ncomp > 0: logger.info(' Created an SSP operator (subspace dimension' ' = %d)' % ncomp) C = np.dot(P, np.dot(C, P.T)) else: logger.info(' The projection vectors do not apply to these ' 'channels.') fig_cov, axes = plt.subplots(1, len(idx_names), squeeze=False, figsize=(3.8 * len(idx_names), 3.7)) for k, (idx, name, _, _, _) in enumerate(idx_names): vlim = np.max(np.abs(C[idx][:, idx])) im = axes[0, k].imshow(C[idx][:, idx], interpolation="nearest", norm=Normalize(vmin=-vlim, vmax=vlim), cmap='RdBu_r') axes[0, k].set(title=name) if colorbar: from mpl_toolkits.axes_grid1 import make_axes_locatable divider = make_axes_locatable(axes[0, k]) cax = divider.append_axes("right", size="5.5%", pad=0.05) plt.colorbar(im, cax=cax, format='%.0e') fig_cov.subplots_adjust(0.04, 0.0, 0.98, 0.94, 0.2, 0.26) tight_layout(fig=fig_cov) fig_svd = None if show_svd: fig_svd, axes = plt.subplots(1, len(idx_names), squeeze=False, figsize=(3.8 * len(idx_names), 3.7)) for k, (idx, name, unit, scaling, key) in enumerate(idx_names): this_C = C[idx][:, idx] s = linalg.svd(this_C, compute_uv=False) this_C = Covariance(this_C, [info['ch_names'][ii] for ii in idx], [], [], 0) this_info = pick_info(info, idx) this_info['projs'] = [] this_rank = compute_rank(this_C, info=this_info) # Protect against true zero singular values s[s <= 0] = 1e-10 * s[s > 0].min() s = np.sqrt(s) * scaling axes[0, k].plot(s, color='k', zorder=3) this_rank = this_rank[key] axes[0, k].axvline(this_rank - 1, ls='--', color='r', alpha=0.5, zorder=4, clip_on=False) axes[0, k].text(this_rank - 1, axes[0, k].get_ylim()[1], 'rank ≈ %d' % (this_rank,), ha='right', va='top', color='r', alpha=0.5, zorder=4) axes[0, k].set(ylabel=u'Noise σ (%s)' % unit, yscale='log', xlabel='Eigenvalue index', title=name, xlim=[0, len(s) - 1]) tight_layout(fig=fig_svd) plt_show(show) return fig_cov, fig_svd
def txrx_plot(true_V, pred_V, mode=None, save_dir='.', suffix=None, params=None): """ Plot relative error (in log10 scale) of true equivalent resistivity and predictive equivalent resistivity, and arrange the result by transmitter pairs and receiver pairs. Parameters ---------- true_V : numpy.ndarray True equivalent resistivity (Potential difference divided by current, ground truth). pred_V : numpy.ndarray Predictive equivalent resistivity. mode : str Select the mode to manipulate the drawing. 'save': save image. 'show': show on screen. Others: return figure object. save_dir : str The directory where figures are saved. suffix : str The suffix string for 'crossplot_' when 'Save' mode is selected. params : dict Dictionary of matplotlib's rcParams to manipulate plot setting. Returns ------- fig : matplotlib.figure.Figure or None The fig is returned when mode is neither 'save' nor 'show'. """ misfit_percent = ((pred_V - true_V) / true_V) * 100 _params = { 'image.aspect': 'auto', 'image.cmap': 'bwr', 'image.origin': 'lower' } if isinstance(params, dict): _params.update(params) get_rcParams(_params, figsize='l') # set properties vmin, vmax = -100, 100 extent = (0.5, true_V.shape[1] + 0.5, 0.5, true_V.shape[0] + 0.5) cbar_size, cbar_pad = '5%', 0.6 # plot fig, ax = plt.subplots(nrows=1, ncols=1) im = ax.imshow(misfit_percent, vmin=vmin, vmax=vmax, extent=extent) divider = make_axes_locatable(ax) cax = divider.append_axes('bottom', size=cbar_size, pad=cbar_pad) cbar = fig.colorbar(im, cax=cax, orientation='horizontal') cbar.set_label('Misfit of resistance (%)') ax.set_title('Data Misfit') ax.set_xlabel('Receiver ID') ax.set_ylabel('Transmitter ID') if mode == 'save': if not os.path.isdir(save_dir): os.makedirs(save_dir, exist_ok=True) filename = 'txrx_{}'.format(suffix) fullname = os.path.join(save_dir, filename) fig.savefig(fullname) plt.close(fig) mpl.rcdefaults() elif mode == 'show': plt.draw() plt.show() mpl.rcdefaults() else: plt.draw() mpl.rcdefaults() return fig
fig1, ax1 = plt.subplots(figsize=(16, 9)) chH = np.ma.masked_invalid(chH) heatmap = ax1.imshow(chH.T, cmap='RdYlBu', vmin=cmin, vmax=cmax, aspect='auto') ax1.patch.set(hatch='///', edgecolor='black', fill=False, snap=False) plt.title(ch.GetTitle(), size=24.) plt.xlabel("Days since September 1st 2020", size=24.) plt.ylabel("Station ID", size=24.) plt.xticks(fontsize=18) plt.yticks(fontsize=18) ax1.set_yticks(np.arange(chH.shape[1]), minor=False) ax1.set_yticklabels(stLabel, minor=False) divider = make_axes_locatable(ax1) cax = divider.append_axes("right", size="5%", pad=0.05) cbar = fig1.colorbar(heatmap, cax=cax) cbar.ax.tick_params(labelsize=18) cbar.set_label("Position of VEM-Charge / FADC", size=18) plt.savefig("../../plots/uBchargePMT" + pmtId + "Hg.pdf", dpi=300) for d in range(1, pk.GetNbinsX() + 1): arr0 = [] for st in range(1, pk.GetNbinsY() + 1): if pk.GetBinContent(d, st) != 0: arr0.append(pk.GetBinContent(d, st)) else: arr0.append(np.nan)
vmax=maskIntensity.max()) plot1 = axarr.imshow( maskIntensity, extent=np.array([qxy.min(), qxy.max(), qz.min(), qz.max()]), aspect=1., norm=colornorm, cmap='inferno', origin='lower', interpolation='none') # 0.1 is for conversion from 1/nm to 1/A axarr.set_title(os.path.basename(tif)) axarr.set_xlabel('q [1/nm]', size=24) axarr.set_ylabel('q [1/nm]', size=24) axarr.tick_params(direction='in', which='major', length=7, labelsize=20) cbar_coord = replace_at_index1( make_axes_locatable(axarr).get_position(), [0, 2], [0.83, 0.02]) cbar_ax = fig.add_axes(cbar_coord) cbar = fig.colorbar(plot1, cax=cbar_ax) cbar_ax.tick_params(direction='out', which='major', length=7, labelsize=20) cbar_ax.tick_params(direction='out', which='minor', length=4) # plt.show() plt.savefig(os.path.join( resultdir, 'png_qxyqz', os.path.basename(tif).replace('.tif', '') + '_qxyqz.pdf'), bbox_inches='tight') plt.close() intensity, q, chi = pg.transform_polar(np.log(img), npt=(qbins, qbins), q_range=(5, 30), chi_range=(-90, 90),
color=color_sink_colmap, markersize=size_sinks[i], alpha=transparence_sink_colmap) ax.set_xlabel(r'$y$ (AU)') ax.set_ylabel(r'$z$ (AU)') plt.xticks(rotation=90) #if title_time==True: #plt.title('Time = '+str(int(simulation_time))+' years') if title_time_cor == True: plt.tight_layout(pad=0.1) #pad en inch si besoin plt.title('Time = ' + str(int(simulation_time - ref[1] * 1e6)) + ' years') # Adding the colorbar divider1 = make_axes_locatable(ax) cax = divider1.append_axes("left", size="6%", pad=0.15) #cax,kw = mpl.colorbar.make_axes([ax],location='left') cbar1 = plt.colorbar(im1, cax=cax) #, **kw) cbar1.ax.yaxis.set_ticks_position('left') cbar1.ax.yaxis.set_label_position('left') cbar1.set_label( r'$\text{log} \left( N \right) \, \, \left( cm^{-2} \right)$') if radius_zoom == 5: plt.xlim([0, lbox_au]) plt.ylim([0, lbox_au]) if save == True: plt.tight_layout(pad=0.1) #pad en inch si besoin plt.savefig(path_save + simu + '_dens_x_' + str(radius_zoom) + '_' + str(num_output) + '.pdf') #, bbox_inches='tight')
def _figure_setup(self, ndim=1, method=None, **kwargs): prefs = self.preferences if not method: method = prefs.method_2D if ndim == 2 else prefs.method_1D ax3d = method in ["surface"] # Get current figure information # ------------------------------ # should we use the previous figure? clear = kwargs.get("clear", True) # is ax in the keywords ? ax = kwargs.pop("ax", None) # is it a twin figure? In such case if ax and hold are also provided, # they will be ignored tax = kwargs.get("twinx", None) if tax is not None: if issubclass(type(tax), mpl.axes.Axes): clear = False ax = tax.twinx() # warning : this currently returns a normal Axes (so units-naive) # TODO: try to solve this ax.name = "main" tax.name = "twin" # the previous main is renamed! self.ndaxes["main"] = ax self.ndaxes["twin"] = tax else: raise ValueError(f"{tax} is not recognized as a valid Axe") self._fig = get_figure(preferences=prefs, **kwargs) if clear: self._ndaxes = {} # reset ndaxes self._divider = None if ax is not None: # ax given in the plot parameters, # in this case we will plot on this ax if issubclass(type(ax), mpl.axes.Axes): ax.name = "main" self.ndaxes["main"] = ax else: raise ValueError( "{} is not recognized as a valid Axe".format(ax)) elif self._fig.get_axes(): # no ax parameters in keywords, so we need to get those existing # We assume that the existing axes have a name self.ndaxes = self._fig.get_axes() else: # or create a new subplot # ax = self._fig.gca(projection=ax3d) :: passing parameters DEPRECATED in matplotlib 3.4 # --- if not ax3d: ax = _Axes(self._fig, 1, 1, 1) ax = self._fig.add_subplot(ax) else: ax = _Axes3D(self._fig) ax = self._fig.add_axes(ax, projection="3d") ax.name = "main" self.ndaxes["main"] = ax # set the prop_cycle according to preference prop_cycle = eval(prefs.axes.prop_cycle) if isinstance(prop_cycle, str): # not yet evaluated prop_cycle = eval(prop_cycle) colors = prop_cycle.by_key()["color"] for i, c in enumerate(colors): try: c = to_rgba(c) colors[i] = c except ValueError: try: c = to_rgba(f"#{c}") colors[i] = c except ValueError as e: raise e linestyles = ["-", "--", ":", "-."] markers = ["o", "s", "^"] if ax is not None and "scatter" in method: ax.set_prop_cycle( cycler("color", colors * len(linestyles) * len(markers)) + cycler("linestyle", linestyles * len(colors) * len(markers)) + cycler("marker", markers * len(colors) * len(linestyles))) elif ax is not None and "scatter" not in method: ax.set_prop_cycle( cycler("color", colors * len(linestyles)) + cycler("linestyle", linestyles * len(colors))) # Get the number of the present figure self._fignum = self._fig.number # for generic plot, we assume only a single axe # with possible projections # and an optional colobar. # other plot class may take care of other needs ax = self.ndaxes["main"] if ndim == 2: # TODO: also the case of 3D # show projections (only useful for map or image) # ------------------------------------------------ self.colorbar = colorbar = kwargs.get("colorbar", prefs.colorbar) proj = kwargs.get("proj", prefs.show_projections) # TODO: tell the axis by title. xproj = kwargs.get("xproj", prefs.show_projection_x) yproj = kwargs.get("yproj", prefs.show_projection_y) SHOWXPROJ = (proj or xproj) and method in ["map", "image"] SHOWYPROJ = (proj or yproj) and method in ["map", "image"] # Create the various axes # ------------------------- # create new axes on the right and on the top of the current axes # The first argument of the new_vertical(new_horizontal) method is # the height (width) of the axes to be created in inches. # # This is necessary for projections and colorbar self._divider = None if (SHOWXPROJ or SHOWYPROJ or colorbar) and self._divider is None: self._divider = make_axes_locatable(ax) divider = self._divider if SHOWXPROJ: axex = divider.append_axes("top", 1.01, pad=0.01, sharex=ax, frameon=0, yticks=[]) axex.tick_params(bottom="off", top="off") plt.setp(axex.get_xticklabels() + axex.get_yticklabels(), visible=False) axex.name = "xproj" self.ndaxes["xproj"] = axex if SHOWYPROJ: axey = divider.append_axes("right", 1.01, pad=0.01, sharey=ax, frameon=0, xticks=[]) axey.tick_params(right="off", left="off") plt.setp(axey.get_xticklabels() + axey.get_yticklabels(), visible=False) axey.name = "yproj" self.ndaxes["yproj"] = axey if colorbar and not ax3d: axec = divider.append_axes("right", 0.15, pad=0.1, frameon=0, xticks=[], yticks=[]) axec.tick_params(right="off", left="off") # plt.setp(axec.get_xticklabels(), visible=False) axec.name = "colorbar" self.ndaxes["colorbar"] = axec return method
def view_profile(p_opt): psix = rt1.psi(p_opt[3], 0.0, separatrix) # psi上のBが最小となる直線上の密度最大値 n1, a1, b1, rm = p_opt nl_y450 = 0.0 nl_z620 = 0.0 nl_z700 = 0.0 nl_y450 = 0.0 for i, x in enumerate(x450): nl_y450 = nl_y450 + np.exp(-a1*abs((psi_x450[i] - psix)/psi0)**2)*n1*dx450 nl_y450 = 2.0*nl_y450 error_y450 = (nl_y450 - nl_y450_mes)**2/(nl_y450_mes)**2 # line integral along vertical y=60, 70 chord nl_z620 = 0.0 for j, z in enumerate(z620): nl_z620 = nl_z620 + n1*np.exp(-a1*abs((psi_z620[j] - psix)/psi0)**2)*(bb620[j]/b0620[j])**(-b1)*dz620 error_z620 = (nl_z620 - nl_z620_mes)**2/(nl_z620_mes)**2 nl_z700 = 0.0 for j, z in enumerate(z700): nl_z700 = nl_z700 + n1*np.exp(-a1*abs((psi_z700[j] - psix)/psi0)**2)*(bb700[j]/b0700[j])**(-b1)*dz700 error_z700 = (nl_z700 - nl_z700_mes)**2/(nl_z700_mes)**2 print ( 'y450: ', nl_y450, '/', nl_y450_mes) print ( 'z620: ', nl_z620, '/', nl_z620_mes) print ( 'z700: ', nl_z700, '/', nl_z700_mes) print ( 'error_y450: ', error_y450) print ( 'error_z620: ', error_z620) print ( 'error_z700: ', error_z700) # Export figure rs = np.linspace( 0.1, 1.001, 200) zs = np.linspace(-0.4, 0.401, 200) r_mesh, z_mesh = np.meshgrid(rs, zs) ne_profile = np.array([list(map(lambda r, z : ne_single_gaussian(r, z, *p_opt_best), r_mesh.ravel(), z_mesh.ravel()))]).ravel().reshape(len(rs), len(zs)) psi_term_profile = np.array([list(map(lambda r, z : psi_term(r, z, *p_opt_best), r_mesh.ravel(), z_mesh.ravel()))]).ravel().reshape(len(rs), len(zs)) B_term_profile = np.array([list(map(lambda r, z : B_term(r, z, *p_opt_best), r_mesh.ravel(), z_mesh.ravel()))]).ravel().reshape(len(rs), len(zs)) psi = np.array([list(map(lambda r, z : rt1.psi(r, z), r_mesh.ravel(), z_mesh.ravel()))]).ravel().reshape(len(rs), len(zs)) coilcase_truth_table = np.array([list(map(lambda r, z : rt1.check_coilcase(r, z), r_mesh.ravel(), z_mesh.ravel()))]).ravel().reshape(len(rs), len(zs)) psi[coilcase_truth_table == True] = 0 #np.save('ne2D_29_fled_r2', ne_profile) ne_profile = np.load("ne2D_35_t10_r1.npy") #ne_profile_t10 = np.load("ne2D_35_t10_r1.npy") #ne_profile_t11 = np.load("ne2D_35_t11_r1.npy") #ne_profile_t15 = np.load("ne2D_35_t15_r1.npy") #ne_profile = ne_profile_t11 - ne_profile_t10 # density profileの表示 levels = [0.005, 0.006, 0.007, 0.008, 0.009, 0.01, 0.011, 0.012, 0.013, 0.014] plt.figure(figsize=(8, 5)) plt.subplot(111) img = plt.imshow(ne_profile, origin='lower', cmap='jet', #img = plt.imshow(ne_profile, origin='lower', cmap=plt.cm.seismic, # norm = MidpointNormalize(midpoint=0), # #vmin=-np.amax(ne_profile), vmax=np.amax(ne_profile), vmax=37, extent=(rs.min(), rs.max(), zs.min(), zs.max())) plt.contour(r_mesh, z_mesh, ne_profile, colors=['k']) plt.contour(r_mesh, z_mesh, psi, colors=['white'], levels=levels) plt.title(r'$n_\mathrm{e}$') plt.xlabel(r'$r\mathrm{\ [m]}$') plt.ylabel(r'$z\mathrm{\ [m]}$') # plt.gca():現在のAxesオブジェクトを返す divider = make_axes_locatable(plt.gca()) # カラーバーの位置 cax = divider.append_axes("right", "5%", pad="3%") cb = plt.colorbar(img, cax=cax) #cb.set_clim(0,6.4) cb.set_label(r'$\mathrm{[10^{16}\,m^{-3}]}$') plt.tight_layout(pad=1.0, w_pad=2.0, h_pad=1.0) plt.show() # psi term profileの表示 plt.figure(figsize=(8, 5)) plt.subplot(111) img = plt.imshow(psi_term_profile, origin='lower', cmap='plasma', extent=(rs.min(), rs.max(), zs.min(), zs.max())) plt.contour(r_mesh, z_mesh, psi_term_profile, colors=['k']) plt.contour(r_mesh, z_mesh, psi, colors=['white'], levels=levels) plt.title(r'$\psi term$') plt.xlabel(r'$r\mathrm{\ [m]}$') plt.ylabel(r'$z\mathrm{\ [m]}$') # plt.gca():現在のAxesオブジェクトを返す divider = make_axes_locatable(plt.gca()) # カラーバーの位置 cax = divider.append_axes("right", "5%", pad="3%") cb = plt.colorbar(img, cax=cax) cb.set_clim(0,6.4) cb.set_label(r'$\mathrm{[10^{16}\,m^{-3}]}$') plt.tight_layout(pad=1.0, w_pad=2.0, h_pad=1.0) plt.show() # B term profileの表示 plt.figure(figsize=(8, 5)) plt.subplot(111) img = plt.imshow(B_term_profile, origin='lower', cmap='plasma', extent=(rs.min(), rs.max(), zs.min(), zs.max())) plt.contour(r_mesh, z_mesh, B_term_profile, colors=['k']) plt.contour(r_mesh, z_mesh, psi, colors=['white'], levels=levels) plt.title(r'$B term$') plt.xlabel(r'$r\mathrm{\ [m]}$') plt.ylabel(r'$z\mathrm{\ [m]}$') # plt.gca():現在のAxesオブジェクトを返す divider = make_axes_locatable(plt.gca()) # カラーバーの位置 cax = divider.append_axes("right", "5%", pad="3%") cb = plt.colorbar(img, cax=cax) cb.set_clim(0,6.4) cb.set_label(r'$\mathrm{[10^{16}\,m^{-3}]}$') plt.tight_layout(pad=1.0, w_pad=2.0, h_pad=1.0) plt.show() # profile_zでのdensity profileの表示 profile_z = 0.0 # プロファイルが見たい任意のz [m] profile_z_index = np.searchsorted(zs, profile_z) ne_profile_z0 = ne_profile[:][profile_z_index] fig, ax = plt.subplots(1) ax.plot(rs, ne_profile_z0) plt.draw() plt.show()
def heatmap_synth(iterator, mode=None, save_dir='.', params=None): """ Heatmap of synthetic resistivity and predictive resistivity. Parameters ---------- iterator : iterator of os.DirEntry objects For iterating all pkl file in certain directory. mode : str Select the mode to manipulate the drawing. 'save': save image. 'show': show on screen. Others: return figure object. save_dir : str The directory where figures are saved. params : dict Dictionary of matplotlib's rcParams to manipulate plot setting. Returns ------- fig : matplotlib.figure.Figure or None The fig is returned when mode is neither 'save' nor 'show'. References ---------- https://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.histogram2d.html https://stackoverflow.com/questions/17237000/create-a-stacked-2d-histogram-using-different-weights """ # setting # for calculating 2d histogram heatmap = 0 # initialize heatmap start, stop, num_edge = -2, 6, 161 xedges = np.linspace(start, stop, num_edge) yedges = np.linspace(start, stop, num_edge) remain = 5 # for crop_zeros # for metric MSE = 0 # mean squared error # for plotting _params = { 'image.cmap': 'jet', 'lines.linewidth': 2, 'lines.linestyle': '--' } # predefined rcParams # color bar cbar_size, cbar_pad = '3%', 0.1 # read data in specific directory and calculate 2d histogram for tmp, file in enumerate(iterator): data = read_pkl(file.path) synthetic_resistivity_log10 = data[ 'synthetic_resistivity_log10'].flatten() predicted_resistivity_log10 = data[ 'predicted_resistivity_log10'].flatten() hist, xedges, yedges = np.histogram2d(synthetic_resistivity_log10, predicted_resistivity_log10, bins=(xedges, yedges)) heatmap += hist MSE += np.square( np.subtract(synthetic_resistivity_log10, predicted_resistivity_log10)).sum() try: MSE = MSE / ( (tmp + 1) * synthetic_resistivity_log10.size) # mean squared error except NameError: raise ValueError('The iterator reaches the end or is empty.') bound = crop_zeros(heatmap, remain=remain, return_bound='only_bound') heatmap = heatmap[bound[0]:bound[1], bound[0]:bound[1]] xedges = xedges[bound[0]:bound[1] + 1] yedges = yedges[bound[0]:bound[1] + 1] # update rcParams if isinstance(params, dict): _params.update(params) get_rcParams(_params, figsize='s') fig, ax = plt.subplots() # heatmap X, Y = np.meshgrid(xedges, yedges) im = ax.pcolormesh(X, Y, heatmap, norm=mpl.colors.LogNorm()) divider = make_axes_locatable(ax) cax = divider.append_axes('right', size=cbar_size, pad=cbar_pad) cbar = fig.colorbar(im, cax=cax) cbar.set_label('Count') # diagonal line ax.plot([xedges[0 + remain], xedges[-1 - remain]], [yedges[0 + remain], yedges[-1 - remain]]) metrics_str = 'MSE: {:{width}.{prec}f}'.format(MSE, width=6, prec=4) props = dict(boxstyle='round', facecolor=(1, 0.5, 0.5), alpha=0.5) ax.text(xedges[0] + 0.05 * (xedges[-1] - xedges[0]), xedges[-1] - 0.05 * (xedges[-1] - xedges[0]), metrics_str, bbox=props, va='top', ha='left') # adjust property ax.set_aspect('equal', adjustable='box') ax.set_xlabel(r'Synthetic resistivity $(\Omega \bullet m,\/log_{10})$') ax.set_ylabel(r'Predicted resistivity $(\Omega \bullet m,\/log_{10})$') fig.tight_layout() # different mode if mode == 'save': if not os.path.isdir(save_dir): os.makedirs(save_dir, exist_ok=True) fullname = os.path.join(save_dir, 'heatmap') fig.savefig(fullname) plt.close(fig) mpl.rcdefaults() elif mode == 'show': plt.draw() plt.show() mpl.rcdefaults() else: plt.draw() mpl.rcdefaults() return fig
wx, wy = som.convert_map_to_euclidean(w) wy = wy * 2 / np.sqrt(3) * 3 / 4 plt.plot(wx, wy, markers[y[cnt]], markerfacecolor='None', markeredgecolor=colors[y[cnt]], markersize=12, markeredgewidth=2) xrange = np.arange(weights.shape[0]) yrange = np.arange(weights.shape[1]) plt.xticks(xrange - .5, xrange) plt.yticks(yrange * 2 / np.sqrt(3) * 3 / 4, yrange) divider = make_axes_locatable(plt.gca()) ax_cb = divider.new_horizontal(size="5%", pad=0.05) cb1 = colorbar.ColorbarBase(ax_cb, cmap=cm.Greys, orientation='vertical', alpha=.4) cb1.ax.get_yaxis().labelpad = 16 cb1.ax.set_ylabel('distance from neurons in the neighbourhood', rotation=270, fontsize=16) plt.gcf().add_axes(ax_cb) legend_elements = [ Line2D([0], [0], marker='o', color='r',
def imview(img, title=None, copy=True, fltscl=False, intrp='nearest', norm=None, cbar=False, cmap=None, fgsz=None, fgnm=None, fig=None, ax=None): """ Display an image. Pixel values are displayed when the pointer is over valid image data. If a figure object is specified then the image is drawn in that figure, and ``fig.show()`` is not called. The figure is closed on key entry 'q'. Parameters ---------- img : array_like, shape (Nr, Nc) or (Nr, Nc, 3) or (Nr, Nc, 4) Image to display title : string, optional (default None) Figure title copy : boolean, optional (default True) If True, create a copy of input `img` as a reference for displayed pixel values, ensuring that displayed values do not change when the array changes in the calling scope. Set this flag to False if the overhead of an additional copy of the input image is not acceptable. fltscl : boolean, optional (default False) If True, rescale and shift floating point arrays to [0,1] intrp : string, optional (default 'nearest') Specify type of interpolation used to display image (see ``interpolation`` parameter of :meth:`matplotlib.axes.Axes.imshow`) norm : :class:`matplotlib.colors.Normalize` object, optional (default None) Specify the :class:`matplotlib.colors.Normalize` instance used to scale pixel values for input to the colour map cbar : boolean, optional (default False) Flag indicating whether to display colorbar cmap : :class:`matplotlib.colors.Colormap`, optional (default None) Colour map for image. If none specifed, defaults to cm.Greys_r for monochrome image fgsz : tuple (width,height), optional (default None) Specify figure dimensions in inches fgnm : integer, optional (default None) Figure number of figure fig : :class:`matplotlib.figure.Figure` object, optional (default None) Draw in specified figure instead of creating one ax : :class:`matplotlib.axes.Axes` object, optional (default None) Plot in specified axes instead of current axes of figure Returns ------- fig : :class:`matplotlib.figure.Figure` object Figure object for this figure ax : :class:`matplotlib.axes.Axes` object Axes object for this plot """ if img.ndim > 2 and img.shape[2] != 3: raise ValueError('Argument img must be an Nr x Nc array or an ' 'Nr x Nc x 3 array') figp = fig if fig is None: fig = plt.figure(num=fgnm, figsize=fgsz) fig.clf() ax = fig.gca() elif ax is None: ax = fig.gca() ax.set_adjustable('box') imgd = img.copy() if copy: # Keep a separate copy of the input image so that the original # pixel values can be display rather than the scaled pixel # values that are actually plotted. img = img.copy() if cmap is None and img.ndim == 2: cmap = cm.Greys_r if np.issubdtype(img.dtype, np.floating): if fltscl: imgd -= imgd.min() imgd /= imgd.max() if img.ndim > 2: imgd = np.clip(imgd, 0.0, 1.0) elif img.dtype == np.uint16: imgd = np.float16(imgd) / np.iinfo(np.uint16).max elif img.dtype == np.int16: imgd = np.float16(imgd) - imgd.min() imgd /= imgd.max() if norm is None: im = ax.imshow(imgd, cmap=cmap, interpolation=intrp, vmin=imgd.min(), vmax=imgd.max()) else: im = ax.imshow(imgd, cmap=cmap, interpolation=intrp, norm=norm) ax.set_yticklabels([]) ax.set_xticklabels([]) if title is not None: ax.set_title(title) if cbar or cbar is None: orient = 'vertical' if img.shape[0] >= img.shape[1] else 'horizontal' pos = 'right' if orient == 'vertical' else 'bottom' divider = make_axes_locatable(ax) cax = divider.append_axes(pos, size="5%", pad=0.2) if cbar is None: # See http://chris35wills.github.io/matplotlib_axis if hasattr(cax, 'set_facecolor'): cax.set_facecolor('none') else: cax.set_axis_bgcolor('none') for axis in ['top', 'bottom', 'left', 'right']: cax.spines[axis].set_linewidth(0) cax.set_xticks([]) cax.set_yticks([]) else: plt.colorbar(im, ax=ax, cax=cax, orientation=orient) def format_coord(x, y): nr, nc = imgd.shape[0:2] col = int(x + 0.5) row = int(y + 0.5) if col >= 0 and col < nc and row >= 0 and row < nr: z = img[row, col] if imgd.ndim == 2: return 'x=%6.2f, y=%6.2f, z=%.2f' % (x, y, z) else: return 'x=%6.2f, y=%6.2f, z=(%.2f,%.2f,%.2f)' % \ sum(((x,), (y,), tuple(z)), ()) else: return 'x=%.2f, y=%.2f' % (x, y) ax.format_coord = format_coord if fig.canvas.toolbar is not None: # See https://stackoverflow.com/a/47086132 def mouse_move(self, event): if event.inaxes and event.inaxes.get_navigate(): s = event.inaxes.format_coord(event.xdata, event.ydata) self.set_message(s) mouse_move_patch = lambda arg: mouse_move(fig.canvas.toolbar, arg) fig.canvas.toolbar._idDrag = fig.canvas.mpl_connect( 'motion_notify_event', mouse_move_patch) attach_keypress(fig) if have_mpldc: mpldc.datacursor(display='single') if figp is None: fig.show() return fig, ax
def contour(z, x=None, y=None, v=5, xlbl=None, ylbl=None, title=None, cfntsz=10, lfntsz=None, intrp='bicubic', alpha=0.5, cmap=None, vmin=None, vmax=None, fgsz=None, fgnm=None, fig=None, ax=None): """ Contour plot of a 2D surface. If a figure object is specified then the plot is drawn in that figure, and ``fig.show()`` is not called. The figure is closed on key entry 'q'. Parameters ---------- z : array_like 2d array of data to plot x : array_like, optional (default None) Values for x-axis of the plot y : array_like, optional (default None) Values for y-axis of the plot v : int or sequence of ints, optional (default 5) An int specifies the number of contours to plot, and a sequence specifies the specific contour levels to plot. xlbl : string, optional (default None) Label for x-axis ylbl : string, optional (default None) Label for y-axis title : string, optional (default None) Figure title cfntsz : int or None, optional (default 10) Contour label font size. No contour labels are displayed if set to 0 or None. lfntsz : int, optional (default None) Axis label font size. The default font size is used if set to None. intrp : string, optional (default 'bicubic') Specify type of interpolation used to display image underlying contours (see ``interpolation`` parameter of :meth:`matplotlib.axes.Axes.imshow`) alpha : float, optional (default 0.5) Underlying image display alpha value cmap : :class:`matplotlib.colors.Colormap`, optional (default None) Colour map for surface. If none specifed, defaults to cm.coolwarm vmin, vmax : float, optional (default None) Set upper and lower bounds for the colour map (see the corresponding parameters of :meth:`matplotlib.axes.Axes.imshow`) fgsz : tuple (width,height), optional (default None) Specify figure dimensions in inches fgnm : integer, optional (default None) Figure number of figure fig : :class:`matplotlib.figure.Figure` object, optional (default None) Draw in specified figure instead of creating one ax : :class:`matplotlib.axes.Axes` object, optional (default None) Plot in specified axes instead of current axes of figure Returns ------- fig : :class:`matplotlib.figure.Figure` object Figure object for this figure ax : :class:`matplotlib.axes.Axes` object Axes object for this plot """ figp = fig if fig is None: fig = plt.figure(num=fgnm, figsize=fgsz) fig.clf() ax = fig.gca() elif ax is None: ax = fig.gca() if cmap is None: cmap = cm.coolwarm if x is None: x = np.arange(z.shape[1]) else: x = np.array(x) if y is None: y = np.arange(z.shape[0]) else: y = np.array(y) xg, yg = np.meshgrid(x, y) cntr = ax.contour(xg, yg, z, v, colors='black') if cfntsz is not None and cfntsz > 0: plt.clabel(cntr, inline=True, fontsize=cfntsz) im = ax.imshow(z, origin='lower', interpolation=intrp, aspect='auto', extent=[x.min(), x.max(), y.min(), y.max()], cmap=cmap, vmin=vmin, vmax=vmax, alpha=alpha) if title is not None: ax.set_title(title) if xlbl is not None: ax.set_xlabel(xlbl, fontsize=lfntsz) if ylbl is not None: ax.set_ylabel(ylbl, fontsize=lfntsz) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.2) plt.colorbar(im, ax=ax, cax=cax) attach_keypress(fig) if have_mpldc: mpldc.datacursor() if figp is None: fig.show() return fig, ax
def structureplot_synth(synth_log_rho, pred_log_rho, xz, mode=None, save_dir='.', suffix=None, params=None): """ Plot synthetic resistivity and predictive resistivity to illustrate subsurface structure. Parameters ---------- synth_log_rho : numpy.ndarray Synthetic resistivity (ground truth). pred_log_rho : numpy.ndarray Predictive resistivity. xz : numpy.ndarray Electrode coordinates. (x, z) mode : str Select the mode to manipulate the drawing. 'save': save image. 'show': show on screen. Others: return figure object. save_dir : str The directory where figures are saved. suffix : str The suffix string for 'structureplot_' when 'Save' mode is selected. params : dict Dictionary of matplotlib's rcParams to manipulate plot setting. Returns ------- fig : matplotlib.figure.Figure or None The fig is returned when mode is neither 'save' nor 'show'. """ _params = { 'image.aspect': 'auto', 'image.cmap': 'jet', 'lines.linestyle': 'None', 'lines.marker': '.', 'lines.markeredgecolor': 'k', 'lines.markerfacecolor': 'k', 'lines.markersize': '4.0' } if isinstance(params, dict): _params.update(params) get_rcParams(_params, figsize='l') fig, (ax0, ax1) = plt.subplots(nrows=2, ncols=1) ax0.plot(xz[:, 0], -xz[:, 1], clip_on=False, zorder=100) # for electrodes ax1.plot(xz[:, 0], -xz[:, 1], clip_on=False, zorder=100) # for electrodes # set properties levels = np.linspace(1, 3, 17, endpoint=True) nz, nx = pred_log_rho.shape vmin, vmax = 1, 3 extent = (0, nx, nz, 0) cbar_size, cbar_pad = '3%', 0.1 # plot synthetic resistivity im0 = ax0.imshow(synth_log_rho, vmin=vmin, vmax=vmax, extent=extent) divider = make_axes_locatable(ax0) cax = divider.append_axes('right', size=cbar_size, pad=cbar_pad) cbar0 = fig.colorbar(im0, cax=cax, extend='both') cbar0.set_label(r'$\Omega-m (log_{10}\/scale)$') ax0.set_title('Synthetic resistivity') ax0.set_ylabel('Depth (m)') # plot predictive resistivity im1 = ax1.contourf(np.flipud(pred_log_rho), levels=levels, extent=extent, extend='both') ax1.invert_yaxis() divider = make_axes_locatable(ax1) cax = divider.append_axes("right", size=cbar_size, pad=cbar_pad) cbar1 = fig.colorbar(im1, cax=cax) cbar1.set_label(r'$\Omega-m (log_{10}\/scale)$') ax1.set_title('Predictive resistivity') ax1.set_xlabel('Width (m)') ax1.set_ylabel('Depth (m)') fig.tight_layout() if mode == 'save': if not os.path.isdir(save_dir): os.makedirs(save_dir, exist_ok=True) filename = 'structureplot_{}'.format(suffix) fullname = os.path.join(save_dir, filename) fig.savefig(fullname) plt.close(fig) mpl.rcdefaults() elif mode == 'show': plt.draw() plt.show() mpl.rcdefaults() else: plt.draw() mpl.rcdefaults() return fig
def plot(self, im): """ Plots and call auxfun_drag class for moving and removing points. """ # small hack in case there are any 0 intensity images! img = io.imread(im) maxIntensity = np.max(img) if maxIntensity == 0: maxIntensity = np.max(img) + 255 divider = make_axes_locatable(self.axes) cax = divider.append_axes("right", size="5%", pad=0.05) self.drs = [] if (self.visualization_rdb.GetSelection() == 0 ): # i.e. for color scheme for individuals self.Colorscheme = visualization.get_cmap( len(self.individual_names), self.cfg["colormap"]) self.norm, self.colorIndex = self.image_panel.getColorIndices( im, self.individual_names) cbar = self.figure.colorbar(self.ax, cax=cax, spacing="proportional", ticks=self.colorIndex) cbar.set_ticklabels(self.individual_names) else: # i.e. for color scheme for all bodyparts self.Colorscheme = visualization.get_cmap(len(self.all_bodyparts), self.cfg["colormap"]) self.norm, self.colorIndex = self.image_panel.getColorIndices( im, self.all_bodyparts) cbar = self.figure.colorbar(self.ax, cax=cax, spacing="proportional", ticks=self.colorIndex) cbar.set_ticklabels(self.all_bodyparts) for ci, ind in enumerate(self.individual_names): col_idx = ( 0 # variable for iterating through the colorscheme for all bodyparts ) image_points = [] if ind == "single": if self.visualization_rdb.GetSelection() == 0: for c, bp in enumerate(self.uniquebodyparts): self.points = [ self.Dataframe[self.scorer][ind][bp]["x"].values[ self.iter], self.Dataframe[self.scorer][ind][bp]["y"].values[ self.iter], self.Dataframe[self.scorer][ind][bp] ["likelihood"].values[self.iter], ] self.likelihood = self.points[2] # fix move to corner if self.move2corner: ny, nx = np.shape(img)[0], np.shape(img)[1] if self.points[0] > nx or self.points[0] < 0: print("fixing x for ", bp) self.points[0] = self.center[0] if self.points[1] > ny or self.points[1] < 0: print("fixing y for ", bp) self.points[1] = self.center[1] if self.likelihood < self.threshold: self.circle = [ patches.Circle( (self.points[0], self.points[1]), radius=self.markerSize, facecolor="None", edgecolor=self.Colorscheme(ci), alpha=self.alpha, ) ] else: self.circle = [ patches.Circle( (self.points[0], self.points[1]), radius=self.markerSize, fc=self.Colorscheme(ci), alpha=self.alpha, ) ] self.axes.add_patch(self.circle[0]) self.dr = auxfun_drag.DraggablePoint( self.circle[0], bp, individual_names=ind, likelihood=self.likelihood, ) self.dr.connect() self.dr.coords = MainFrame.getLabels( self, self.iter, ind, self.uniquebodyparts)[c] self.drs.append(self.dr) self.updatedCoords.append(self.dr.coords) else: for c, bp in enumerate(self.uniquebodyparts): self.points = [ self.Dataframe[self.scorer][ind][bp]["x"].values[ self.iter], self.Dataframe[self.scorer][ind][bp]["y"].values[ self.iter], self.Dataframe[self.scorer][ind][bp] ["likelihood"].values[self.iter], ] self.likelihood = self.points[2] # fix move to corner if self.move2corner: ny, nx = np.shape(img)[0], np.shape(img)[1] if self.points[0] > nx or self.points[0] < 0: print("fixing x for ", bp) self.points[0] = self.center[0] if self.points[1] > ny or self.points[1] < 0: print("fixing y for ", bp) self.points[1] = self.center[1] if self.likelihood < self.threshold: self.circle = [ patches.Circle( (self.points[0], self.points[1]), radius=self.markerSize, fc="None", edgecolor=self.Colorscheme(col_idx), alpha=self.alpha, ) ] else: self.circle = [ patches.Circle( (self.points[0], self.points[1]), radius=self.markerSize, fc=self.Colorscheme(col_idx), alpha=self.alpha, ) ] self.axes.add_patch(self.circle[0]) col_idx = col_idx + 1 self.dr = auxfun_drag.DraggablePoint( self.circle[0], bp, individual_names=ind, likelihood=self.likelihood, ) self.dr.connect() self.dr.coords = MainFrame.getLabels( self, self.iter, ind, self.uniquebodyparts)[c] self.drs.append(self.dr) self.updatedCoords.append(self.dr.coords) else: if self.visualization_rdb.GetSelection() == 0: for c, bp in enumerate(self.multianimalbodyparts): self.points = [ self.Dataframe[self.scorer][ind][bp]["x"].values[ self.iter], self.Dataframe[self.scorer][ind][bp]["y"].values[ self.iter], self.Dataframe[self.scorer][ind][bp] ["likelihood"].values[self.iter], ] self.likelihood = self.points[2] # fix move to corner if self.move2corner: ny, nx = np.shape(img)[0], np.shape(img)[1] if self.points[0] > nx or self.points[0] < 0: print("fixing x for ", bp) self.points[0] = self.center[0] if self.points[1] > ny or self.points[1] < 0: print("fixing y for ", bp) self.points[1] = self.center[1] if self.likelihood < self.threshold: self.circle = [ patches.Circle( (self.points[0], self.points[1]), radius=self.markerSize, fc="None", edgecolor=self.Colorscheme(ci), alpha=self.alpha, ) ] else: self.circle = [ patches.Circle( (self.points[0], self.points[1]), radius=self.markerSize, fc=self.Colorscheme(ci), alpha=self.alpha, ) ] self.axes.add_patch(self.circle[0]) self.dr = auxfun_drag.DraggablePoint( self.circle[0], bp, individual_names=ind, likelihood=self.likelihood, ) self.dr.connect() self.dr.coords = MainFrame.getLabels( self, self.iter, ind, self.multianimalbodyparts)[c] self.drs.append(self.dr) self.updatedCoords.append(self.dr.coords) else: for c, bp in enumerate(self.multianimalbodyparts): self.points = [ self.Dataframe[self.scorer][ind][bp]["x"].values[ self.iter], self.Dataframe[self.scorer][ind][bp]["y"].values[ self.iter], self.Dataframe[self.scorer][ind][bp] ["likelihood"].values[self.iter], ] self.likelihood = self.points[2] # fix move to corner if self.move2corner: ny, nx = np.shape(img)[0], np.shape(img)[1] if self.points[0] > nx or self.points[0] < 0: print("fixing x for ", bp) self.points[0] = self.center[0] if self.points[1] > ny or self.points[1] < 0: print("fixing y for ", bp) self.points[1] = self.center[1] if self.likelihood < self.threshold: self.circle = [ patches.Circle( (self.points[0], self.points[1]), radius=self.markerSize, fc="None", edgecolor=self.Colorscheme(col_idx), alpha=self.alpha, ) ] else: self.circle = [ patches.Circle( (self.points[0], self.points[1]), radius=self.markerSize, fc=self.Colorscheme(col_idx), alpha=self.alpha, ) ] self.axes.add_patch(self.circle[0]) col_idx = col_idx + 1 self.dr = auxfun_drag.DraggablePoint( self.circle[0], bp, individual_names=ind, likelihood=self.likelihood, ) self.dr.connect() self.dr.coords = MainFrame.getLabels( self, self.iter, ind, self.multianimalbodyparts)[c] self.drs.append(self.dr) self.updatedCoords.append(self.dr.coords) self.figure.canvas.draw()
fig, ax = newfig(1.0, 0.6) ax.axis('off') ######## Row 2: Pressure ####################### ######## Predicted p(t,x,y) ########### gs = gridspec.GridSpec(1, 2) gs.update(top=0.8, bottom=0.2, left=0.1, right=0.9, wspace=0.5) ax = plt.subplot(gs[:, 0]) h = ax.imshow(Exact_sol, interpolation='nearest', cmap='jet', extent=[lb_sol[0], ub_sol[0], lb_sol[1], ub_sol[1]], origin='lower', aspect='auto') divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) fig.colorbar(h, cax=cax) ax.set_xlabel('$t$') ax.set_ylabel('$x$') ax.set_title('Exact Dynamics', fontsize=10) line = np.linspace(lb_sol[1], ub_sol[1], 2)[:, None] ax.plot(t_idn[index] * np.ones((2, 1)), line, 'w-', linewidth=1) ######## Exact p(t,x,y) ########### ax = plt.subplot(gs[:, 1]) h = ax.imshow(U_pred, interpolation='nearest', cmap='jet',
def heatmap_main(self, truths, plot_range, destination): """main heatmap plot -define custom compression colourmap - Parameters ------ truths : array_like `truth` true positions plot_range : list `plot_range` what range of time points (indices) from truths to plot. """ ukf_params = self.filter_class.ukf_params """Setting up custom colour map. defining bottom value (0) to be black and everything else is just cividis """ cmap = cm.cividis cmaplist = [cmap(i) for i in range(cmap.N)] cmaplist[0] = (0.0, 0.0, 0.0, 1.0) cmap = col.LinearSegmentedColormap("custom_cmap", cmaplist, N=cmap.N) cmap = cmap.from_list("custom", cmaplist) """ TLDR: compression norm allows for more interesting colouration of heatmap For a large number of grid squares most of the squares only have a few agents in them ~5. If we have 30 agents this means roughly 2/3rds of the colourmap is not used and results in very boring looking graphs. In these cases I suggest we `move` the colourbar so more of it covers the bottom 1/3rd and we get a more colour `efficient` graph. n_prop function makes colouration linear for low pops and large square sizes but squeezes colouration into the bottom of the data range for higher pops/low bins. This squeezing is proportional to the sech^2(x) = (1-tanh^2(x)) function for x>=0. (Used tanh identity as theres no sech function in numpy.) http://mathworld.wolfram.com/HyperbolicSecant.html It starts near 1 so 90% of the colouration initially covers 90% of the data range (I.E. linear colouration). As x gets larger sech^2(x) decays quickly to 0 so 90% of the colouration covers a smaller percentage of the data range. E.g if x = 1, n = 30, 30*0.9*sech^2(1) ~= 10 so 90% of the colouration would be used for the bottom 10 agents and much more of the colour bar would be used. There's probably a nice kernel alternative to sech """ n = self.filter_class.model_params["pop_total"] n_prop = n * (1 - np.tanh(n / ukf_params["bin_size"])**2) norm = CompressionNorm(1e-5, 0.9 * n_prop, 0.1, 0.9, 1e-8, n) sm = cm.ScalarMappable(norm=norm, cmap=cmap) sm.set_array([]) for i in plot_range: locs = truths[i, :] counts = poly_count(ukf_params["poly_list"], locs) f = plt.figure(figsize=(12, 8)) ax = f.add_subplot(111) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) "plot density histogram and locations scatter plot assuming at least one agent available" #ax.scatter(locs[0::2],locs[1::2],color="cyan",label="True Positions") ax.set_ylim(0, self.height) ax.set_xlim(0, self.width) #column = frame["counts"].astype(float) #im = frame.plot(column=column, # ax=ax,cmap=cmap,norm=norm,vmin=0,vmax = n) patches = [] for item in ukf_params["poly_list"]: patches.append( mpatches.Polygon(np.array(item.exterior), closed=True)) collection = PatchCollection(patches, cmap=cmap, norm=norm, alpha=1.0, edgecolor="w") ax.add_collection(collection) "if no agents in model for some reason just give a black frame" if np.nansum(counts) != 0: collection.set_array(np.array(counts)) else: collection.set_array(np.zeros(np.array(counts).shape)) for k, count in enumerate(counts): plt.plot ax.annotate(s=count, xy=ukf_params["poly_list"][k].centroid.coords[0], ha='center', va="center", color="w", size=ukf_params["bin_size"]) "set up cbar. colouration proportional to number of agents" ax.text(0, 101, s="Total Agents: " + str(np.sum(counts)), color="k") cbar = plt.colorbar(sm, cax=cax, spacing="proportional") cbar.set_label("Agent Counts") cbar.set_alpha(1) #cbar.draw_all() "set legend to bottom centre outside of plot" box = ax.get_position() ax.set_position([ box.x0, box.y0 + box.height * 0.1, box.width, box.height * 0.9 ]) "labels" ax.set_xlabel("Corridor width") ax.set_ylabel("Corridor height") #ax.set_title("Agent Densities vs True Positions") cbar.set_label(f"Agent Counts (out of {n})") """ frame number and saving. padded zeroes to keep frames in order. padded to nearest upper order of 10 of number of iterations. """ number = str(i).zfill(ceil(log10(truths.shape[0]))) file = destination + self.prefix + f"heatmap_{number}" "show a single frame. dont plot hundreds of them" if len(plot_range) == 1: plt.show() if self.save: f.savefig(file) plt.close()