def plot_scatter_profilesSet(df, profileSet=[], var='CTEMP', wd=7.48, ht=5, varmin=-2, varmax=5, levs=[], show=True, colorunit='$\\theta^{\circ}$C ', save=False, savename="Untitled.png", fontsize=8, zmin=0.0, ticks=[], cline=[], legend_show=True): matplotlib.rcParams.update({'font.size': fontsize}) plt.close(1) fig = plt.figure(1, figsize=(wd, ht)) gs = gridspec.GridSpec(2, 1, height_ratios=[1, 0.05]) ax = plt.subplot(gs[0, 0]) if not profileSet: raise ValueError('profileSet cannot be null!') selectProfiles = df.PROFILE_NUMBER.isin(profileSet) cs = ax.scatter(df.loc[selectProfiles, 'DIST_GLINE'], df.loc[selectProfiles, 'DEPTH'], c=df.loc[selectProfiles, 'CTEMP']) cs_gamman = ax.tricontour(df.loc[selectProfiles, 'DIST_GLINE'], df.loc[selectProfiles, 'DEPTH'], df.loc[selectProfiles, 'gamman'], colors='0.5') distSortedIndices = np.argsort(df.loc[selectProfiles, 'DIST_GLINE']) ax.plot(df.loc[selectProfiles, 'DIST_GLINE'].values[distSortedIndices], df.loc[selectProfiles, 'ECHODEPTH'].values[distSortedIndices], linewidth=4, color='k') if not cline: cline = np.arange(27.8, 28.5, 0.1) ax.clabel(cs_gamman, colors='k', fontsize=14, fmt='%3.2f') colorax = plt.subplot(gs[1, 0]) cbar1 = Colorbar(ax=colorax, mappable=cs, orientation='horizontal') cbar1.ax.get_children()[0].set_linewidths(5) cbar1.set_label(colorunit) if save: plt.savefig(savename, dpi=300) if show: plt.show()
def pmft_plot(pmft, ax=None): """Helper function to draw 2D PMFT diagram. .. moduleauthor:: Jin Soo Ihm <*****@*****.**> Args: pmft (:class:`freud.pmft.PMFTXY2D`): PMFTXY2D instance. ax (:class:`matplotlib.axes.Axes`): axes object to plot. If :code:`None`, make a new axes and figure object. (Default value = :code:`None`). Returns: :class:`matplotlib.axes.Axes`: axes object with the diagram. """ if not MATPLOTLIB: return None try: from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable from matplotlib.colorbar import Colorbar except ImportError: return None else: # Plot figures if ax is None: fig = Figure() ax = fig.subplots() pmft_arr = np.copy(pmft.PMFT) pmft_arr[np.isinf(pmft_arr)] = np.nan xlims = (pmft.X[0], pmft.X[-1]) ylims = (pmft.Y[0], pmft.Y[-1]) ax.set_xlim(xlims) ax.set_ylim(ylims) ax.xaxis.set_ticks([i for i in range(int(xlims[0]), int(xlims[1]+1))]) ax.yaxis.set_ticks([i for i in range(int(ylims[0]), int(ylims[1]+1))]) ax.set_xlabel(r'$x$') ax.set_ylabel(r'$y$') ax.set_title('PMFT') ax_divider = make_axes_locatable(ax) cax = ax_divider.append_axes("right", size="7%", pad="10%") im = ax.imshow(np.flipud(pmft_arr), extent=[xlims[0], xlims[1], ylims[0], ylims[1]], interpolation='nearest', cmap='viridis', vmin=-2.5, vmax=3.0) cb = Colorbar(cax, im) cb.set_label(r"$k_B T$") return ax
def pmft_plot(pmft, ax=None): """Helper function to draw 2D PMFT diagram. Args: pmft (:class:`freud.pmft.PMFTXY2D`): PMFTXY2D instance. ax (:class:`matplotlib.axes.Axes`): Axes object to plot. If :code:`None`, make a new axes and figure object. (Default value = :code:`None`). Returns: :class:`matplotlib.axes.Axes`: Axes object with the diagram. """ from matplotlib.colorbar import Colorbar from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable # Plot figures if ax is None: fig = plt.figure() ax = fig.subplots() pmft_arr = np.copy(pmft.PMFT) pmft_arr[np.isinf(pmft_arr)] = np.nan xlims = (pmft.X[0], pmft.X[-1]) ylims = (pmft.Y[0], pmft.Y[-1]) ax.set_xlim(xlims) ax.set_ylim(ylims) ax.xaxis.set_ticks([i for i in range(int(xlims[0]), int(xlims[1] + 1))]) ax.yaxis.set_ticks([i for i in range(int(ylims[0]), int(ylims[1] + 1))]) ax.set_xlabel(r"$x$") ax.set_ylabel(r"$y$") ax.set_title("PMFT") ax_divider = make_axes_locatable(ax) cax = ax_divider.append_axes("right", size="7%", pad="10%") im = ax.imshow( np.flipud(pmft_arr), extent=[xlims[0], xlims[1], ylims[0], ylims[1]], interpolation="nearest", cmap="viridis", vmin=-2.5, vmax=3.0, ) cb = Colorbar(cax, im) cb.set_label(r"$k_B T$") return ax
def draw_ctag_ratio(in_file, out_dir, ext='.pdf', **opts): """ Heat map showing efficiency ratio gaia and some other tagger. Makes iso-efficiency contours for gaia. misc options: tagger tagger_disp (for display) vmax """ options = {'tagger':'jfc', 'tagger_disp':'JetFitterCharm', 'vmax':1.2, 'num_tagger':'gaia', 'num_tagger_disp':None, 'textsize':_text_size} for key, val in opts.items(): if not key in options: raise TypeError("{} not a valid arg".format(key)) options[key] = val fig = Figure(figsize=_fig_size) canvas = FigureCanvas(fig) ax = fig.add_subplot(1,1,1) ds = in_file['{}/all'.format(options['num_tagger'])] ds_denom = in_file['{}/all'.format(options['tagger'])] eff_array, extent = _get_arr_extent(ds) denom_array, denom_extent = _get_arr_extent(ds_denom) ratio_array = eff_array / denom_array im = ax.imshow(ratio_array.T, extent=extent, origin='lower', aspect='auto', vmin=1.0, vmax=options['vmax']) textsize = options['textsize'] divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) cb = Colorbar(ax=cax, mappable=im) cb.set_label('$\epsilon_{{c}}$ ratio ({} / {})'.format( options['num_tagger_disp'] or options['num_tagger'].upper(), options['tagger_disp']), size=textsize) cb.ax.tick_params(labelsize=textsize, which='both') label_rejrej_axes(ax, ds, textsize=textsize) _add_eq_contour(ax, ds, ds_denom, colorbar=cb) add_contour(ax,ds, opts=dict(textsize=textsize)) out_name = '{}/ctag-2d-{}-vs-{}{}'.format( out_dir, options['num_tagger'], options['tagger'], 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 map_skyobjs(x, y, n, mu, label=None, n_min=10, vmin=None, vmax=None, y_size=4, margin=0.2, fontsize=30, cbar_label=False): """Map the RA, Dec distributions of sky objects.""" # Only keey the bins with enough sky objects in them mu[n <= n_min] = np.nan xy_ratio = (x.max() - x.min()) / (y.max() - y.min()) fig = plt.figure(figsize=(xy_ratio * y_size, y_size)) ax1 = fig.add_subplot(111) ax1.grid(linestyle='--', alpha=0.6) im = ax1.imshow(mu.T, origin='lower', extent=[x[0], x[-1], y[0], y[-1]], aspect='equal', interpolation='nearest', cmap=plt.get_cmap('coolwarm'), vmin=vmin, vmax=vmax) ax1.set_xlim(x.min() - margin, x.max() + margin) ax1.set_ylim(y.min() - margin, y.max() + margin) if label is not None: plt.text(0.03, 1.05, label, transform=ax1.transAxes, fontsize=38) # Color bar cb_axes = fig.add_axes([0.48, 0.90, 0.37, 0.06]) cb = Colorbar(ax=cb_axes, mappable=im, orientation='horizontal', ticklocation='top') if cbar_label: cb.set_label(r'$\mu{\rm Jy}/\mathrm{arcsec}^2$', fontsize=25) _ = ax1.set_xlabel(r'$\mathrm{R.A.\ [deg]}$', fontsize=fontsize) _ = ax1.set_ylabel(r'$\mathrm{Dec\ [deg]}$', fontsize=fontsize) return fig
def draw_ctag_ratio(in_file, out_dir, ext='.pdf', **opts): """ misc options: tagger tagger_disp (for display) vmax """ options = {'tagger':'jfc', 'tagger_disp':'JetFitterCharm', 'vmax':1.2} for key, val in opts.items(): if not key in options: raise TypeError("{} not a valid arg".format(key)) options[key] = val fig = Figure(figsize=(8,6)) canvas = FigureCanvas(fig) ax = fig.add_subplot(1,1,1) ds = in_file['gaia/all'] ds_denom = in_file['{}/all'.format(options['tagger'])] eff_array, extent = _get_arr_extent(ds) denom_array, denom_extent = _get_arr_extent(ds_denom) ratio_array = eff_array / denom_array im = ax.imshow(ratio_array.T, extent=extent, origin='lower', aspect='auto', vmin=1.0, vmax=options['vmax']) ax.set_xscale('log') ax.set_yscale('log') ax.grid(which='both') divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) cb = Colorbar(ax=cax, mappable=im) cb.set_label('$\epsilon_{{c}}$ ratio (GAIA / {})'.format( options['tagger_disp'])) _label_axes(ax, ds) _add_eq_contour(ax, ds, ds_denom, colorbar=cb) _add_contour(ax,ds) out_name = '{}/rejrej-ratio-{}{}'.format( out_dir, options['tagger'], 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 plot_density(density, box, ax=None): R"""Helper function to plot density diagram. Args: density (:math:`\left(N_x, N_y\right)` :class:`numpy.ndarray`): Array containing density. box (:class:`freud.box.Box`): Simulation box. ax (:class:`matplotlib.axes.Axes`): axes object to plot. If :code:`None`, make a new axes and figure object. (Default value = :code:`None`). Returns: :class:`matplotlib.axes.Axes`: axes object with the diagram. """ if not MATPLOTLIB: return None try: from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable from matplotlib.colorbar import Colorbar except ImportError: return None if ax is None: fig = Figure() ax = fig.subplots() xlims = (-box.Lx/2, box.Lx/2) ylims = (-box.Ly/2, box.Ly/2) ax.set_title('Gaussian Density') ax.set_xlabel(r'$x$') ax.set_ylabel(r'$y$') ax_divider = make_axes_locatable(ax) cax = ax_divider.append_axes("right", size="7%", pad="10%") im = ax.imshow(density, extent=[xlims[0], xlims[1], ylims[0], ylims[1]]) cb = Colorbar(cax, im) cb.set_label("Density") return ax
cbax.set_position(pos2) # set a new position cbar_ticks = np.linspace(np.min(image), np.max(image), 8, endpoint=True) cb = Colorbar(ax=cbax, mappable=splot, orientation='vertical', ticklocation='right') plt.xticks(fontsize=14) #cbax.set_yticklabels(["{:4.2f}".format(i) for i in cbar_ticks]) exponent = r'$\times 10^' + str(division) + '$' cb.set_label(r'Flux ' + exponent + r' (e$^-$)', labelpad=10, fontsize=16) plt.savefig('TPF_Gaia_TIC' + tic + '_S' + str(tpf.sector) + '.pdf') # Save Gaia sources info if args.SAVEGAIA: dist = np.sqrt((x - x[this])**2 + (y - y[this])**2) GaiaID = np.array(res['Source']) srt = np.argsort(dist) x, y, gaiamags, dist, GaiaID = x[srt], y[srt], gaiamags[srt], dist[ srt], GaiaID[srt] IDs = np.arange(len(x)) + 1 inside = np.zeros(len(x))
def phase_vs_gacos(int_did, m_date, s_date, i_data, g_data, c_data, dem_data, std_red): logger.info('Generating IFG phase vs GACOS phase estimation: {}_{}'.format(m_date, s_date)) i_data = deepcopy(i_data) g_data = deepcopy(g_data) dem_data = deepcopy(dem_data) i_data[c_data==0] = np.nan g_data[c_data==0] = np.nan dem_data[c_data==0] = np.nan ######################### ## Plotting IFG against GACOS corr #mask = ~np.isnan(i_data) & ~np.isnan(g_data) #x_mask = i_data[mask] #y_mask = g_data[mask] #z_mask = dem_data[mask] # clean outliers index = np.nonzero( np.logical_and(~np.isnan(i_data), np.logical_and(~np.isnan(g_data), np.logical_and(g_data!=0, np.logical_and(i_data!=0, np.logical_and(i_data>np.nanpercentile(i_data, .5), np.logical_and(i_data<np.nanpercentile(i_data, 99.5), np.logical_and(g_data>np.nanpercentile(g_data, .5), g_data<np.nanpercentile(g_data, 99.5) )))))))) # no, the brutal downsampling is just for plotting x = i_data[index].flatten() y = g_data[index].flatten() z = dem_data[index].flatten() if x.size == 0 or y.size ==0: logger.info('MASK ERROR:', m_date, s_date) # curvefit to sliding median with std weighting binned_xdata, running_median, running_std = sliding_median(x, y) def linear_f(x, a, b): return a*x + b # watch out for first element of sliding median equal to NaN try: popt, pcov = curve_fit(linear_f, binned_xdata[1:], running_median[1:], sigma=running_std[1:], absolute_sigma=True) except: try: # Calculate the linear trend, pearson coefficient # linear regression of data slope, intercept, rvalue, pvalue, stderr = linregress(x, y) popt = [slope,intercept] except: popt = np.zeros((2)) logger.critical('Gradient ERROR:', m_date, s_date) # compute correlation m = np.vstack([x,y]) cov = np.corrcoef(m) rvalue = cov[0,1] # plot subsample data data_interval = 10 # First, create the figure (size = x,y) fig = plt.figure(1, figsize=(10, 10)) # Now, create the gridspec structure, as required gs = gridspec.GridSpec(3,2, height_ratios=[0.05, .8, .2], width_ratios=[.8, .2]) # 3 rows, 4 columns, each with the required size ratios. gs.update(left=0.1, right=0.9, bottom=0.1, top=0.9, wspace=0.02, hspace=0.02) # First, the scatter plot # -------------------------------------------------------- ax1 = plt.subplot(gs[1,0]) # place it where it should be. # -------------------------------------------------------- cmax = np.nanpercentile(z, 97.5) cmin = np.nanpercentile(z, 2.5) # The plot itself plt1 = ax1.scatter(x[::data_interval], y[::data_interval], c = z[::data_interval], marker = 's', s = 5, edgecolor = 'none', alpha = 0.05, cmap = cmap, vmin = cmin , vmax = cmax, rasterized=True) ax1.plot(binned_xdata, running_median, color='grey', lw=2) ax1.fill_between(binned_xdata, running_median-running_std, running_median+running_std, color='grey',alpha=0.3) ax1.plot(x, linear_f(x,*popt), color='black', lw=2) # Define the limits, labels, ticks as required ax1.grid(True) ax1.set_axisbelow(True) xlim_buffer = (np.nanpercentile(x, 99.85) - np.nanpercentile(x, 0.15))*0.1 ylim_buffer = (np.nanpercentile(y, 99.85) - np.nanpercentile(y, 0.15))*0.1 ax1.set_xlim(np.nanpercentile(x, 0.15)-xlim_buffer, np.nanpercentile(x, 99.85)+xlim_buffer) ax1.set_ylim(np.nanpercentile(y, 0.15)-ylim_buffer, np.nanpercentile(y, 99.85)+ylim_buffer) ax1.xaxis.set_major_locator(plticker.MultipleLocator(base=5)) ax1.yaxis.set_major_locator(plticker.MultipleLocator(base=5)) ax1.set_ylabel('$\phi_{GACOS}$: '+str(m_date)+'_'+str(s_date)) # scatter labels to fine for legend so... labels = ['Gradient: {:.2f}'.format(popt[0]), 'Correlation: {:.2f}'.format(rvalue), 'STD Reduction: {:.1f}%'.format(std_red)] label_colours = [(0,0,0,0),(0,0,0,0),(0,0,0,0)] recs = [] for i in range(0,len(label_colours)): recs.append(patches.Rectangle((0,0),1,1,fc=label_colours[i])) plt.legend(recs,labels,loc=2) # and let us not forget the colorbar above ! # -------------------------------------------------------- cbax = plt.subplot(gs[0,0]) # Place it where it should be. # -------------------------------------------------------- cb = Colorbar(ax = cbax, mappable = plt1, orientation = 'horizontal', ticklocation = 'top') cb.set_label(r'Elevation (m)', labelpad=10) cb.solids.set(alpha=1) # And now the histogram # -------------------------------------------------------- ax1v = plt.subplot(gs[1,1]) # -------------------------------------------------------- # Plot the data binwidth = 0.1 bins = np.arange(np.nanpercentile(y, 0.15),np.nanpercentile(y, 99.85)+binwidth,binwidth) ax1v.hist(y, bins=bins, orientation='horizontal', color='grey') ax1v.set_xlabel('No. of Pixels') # Define the limits, labels, ticks as required ax1v.set_yticks(ax1.get_yticks()) # Ensures we have the same ticks as the scatter plot ! ax1v.set_yticklabels([]) ax1v.set_ylim(ax1.get_ylim()) #ax1v.xaxis.set_major_locator(plticker.MultipleLocator(base=1000)) ax1v.grid(True) ax1v.set_axisbelow(True) # And now another histogram # -------------------------------------------------------- ax1h = plt.subplot(gs[2,0]) # -------------------------------------------------------- # Plot the data bins = np.arange(np.nanpercentile(x, 0.15),np.nanpercentile(x, 99.85)+binwidth,binwidth) ax1h.hist(x, bins=bins, orientation='vertical', color='grey') ax1h.set_xlabel('$\phi_{IFG} - \phi_{RAMP}$: '+str(m_date)+'_'+str(s_date)) ax1h.set_ylabel(r'No. of pixels') # Define the limits, labels, ticks as required ax1h.set_xticks(ax1.get_xticks()) # Ensures we have the same ticks as the scatter plot ! ax1h.set_xlim(ax1.get_xlim()) #ax1h.yaxis.set_major_locator(plticker.MultipleLocator(base=1000)) ax1h.grid(True) ax1h.set_axisbelow(True) ## Save figure fig.savefig(int_gdir+'/'+int_did+'/'+'phase-gacos'+'_'+str(m_date)+'_'+str(s_date)+'.png', format='PNG', dpi=300, bbox_inches='tight') if plot == 'yes': logger.info('Plotting phase vs. atmos...') plt.show() plt.clf() # Note slope = gradient, rvalue = correlation coefficient return popt[0], rvalue
def plot_station_locations(positions, title=' ', save=False, savename="untitled.png", wd=12, ht=12, region='Whole', plotBathy=True): x = positions[:, 1] y = positions[:, 0] lat0 = -90 lon0 = 0 plt.figure(1, figsize=(wd, ht)) gs = gridspec.GridSpec(2, 1, height_ratios=[1, 0.05]) mapax = plt.subplot(gs[0, 0]) m = createMapProjections(lat0, lon0, region=region) m.drawmapboundary() m.drawcoastlines() #m.fillcontinents(color='#cc9966'); m.readshapefile( "/media/data/Datasets/Shapefiles/AntarcticGroundingLine/GSHHS_f_L6", "GSHHS_f_L6", color='m') ## if(markers != None): ## for i in range(len(markers)): ## plt.text(xgrid[i],ygrid[i], str(markers[i]), color='b'); parallels = np.arange(-80, -30 + 1, 5.) labels = [1, 1, 1, 0] m.drawparallels(parallels, labels=labels) meridians = np.arange(-180, 180, 20.) labels = [1, 1, 0, 1] m.drawmeridians(meridians, labels=labels) m.scatter(x, y, latlon=True, color='r', s=0.25, marker='.') if (plotBathy == True): bathy = xr.open_dataset( '/media/data/Datasets/Bathymetry/GEBCO_2014_2D.nc') lonlen = len(bathy.lon) lonindices = np.arange(0, lonlen + 1, 30) lonindices[-1] = lonindices[-1] - 1 bathyS = bathy.isel(lon=lonindices, lat=np.arange(0, 3600, 5)) clevs = np.array([-100, -500, -1000, -1500, -2000, -3000, -6000])[::-1] longrid, latgrid = np.meshgrid(bathyS.lon.values, bathyS.lat.values) cs = m.contour(longrid, latgrid, bathyS.elevation.where(bathyS.elevation <= 0).values, latlon=True, levels=clevs, linewidths=0.2, extend='min', ax=mapax) #, , cmap='rainbow' , levels=clevs, ## plt.figure(2) ## cf = plt.contourf(longrid, latgrid,bathyS.elevation.where(bathyS.elevation <= 0).values, levels=clevs, extend='min') #, , cmap='rainbow' , levels=clevs, ## plt.figure(1) bathycolorbar = plt.subplot(gs[1, 0]) cbar1 = Colorbar(ax=bathycolorbar, mappable=cs, orientation='horizontal') cbar1.ax.get_children()[0].set_linewidths(5) cbar1.set_label('Depth (m)') if (save == True): plt.savefig(savename, dpi=900) plt.show()
def _overlay_rejrej(array_one, array_two, out_name = 'rejrej.pdf', do_rel = False, do_contour = False, do_abs_contour = False, do_equal_contour = False, z_range = None, extra_cuts=[]): if do_contour and do_abs_contour: warnings.warn("can't do both abs_contour and contour, " "won't use abs_contour") do_abs_contour = False array_one['eff'] = _maximize_efficiency(array_one['eff']) array_two['eff'] = _maximize_efficiency(array_two['eff']) arrays = array_one, array_two # pretty sure the 'nonzero' calls here aren't needed (bool array returned # by the inequality should work) array_one['eff'][np.nonzero(array_one['eff'] <= 0.0)] = np.NaN array_two['eff'][np.nonzero(array_two['eff'] <= 0.0)] = np.NaN if do_rel: old_warn_set = np.seterr(divide = 'ignore') eff_array = array_one['eff'] / array_two['eff'] np.seterr(**old_warn_set) else: eff_array = array_one['eff'] - array_two['eff'] for a in arrays: if not 'tagger' in a: warnings.warn('no tagger name given',stacklevel = 2) a['tagger'] = 'unknown' if _get_rel_plot_alignment(array_one, array_two) > 1e-6: ranges = [(p['x_range'], p['y_range']) for p in arrays] raise ValueError("ranges {} don't match {}".format(*ranges)) if not _check_sig_bg_match(*arrays): err = 'array mismatch ---' for a in arrays: err += 'sig: {signal}, bgx: {x_bg}, bgy: {y_bg} '.format(**a) raise ValueError(err) x_min, x_max = array_one['x_range'] y_min, y_max = array_one['y_range'] fig = plt.figure() gs = GridSpec(20,21) ax = plt.subplot(gs[:,0:-1]) aspect = float(x_max - x_min) / (y_max - y_min) # cmap = mp.colors.Colormap('rainbow') rel_min = np.min(eff_array[np.isfinite(eff_array)]) rel_max = np.max(eff_array[np.isfinite(eff_array)]) if z_range: rel_min, rel_max = z_range if do_abs_contour: contour_array = array_one['eff'] signal = array_one['signal'] contour_range = (0,0.5) if signal == 'charm' else (0.5,1) else: contour_array = eff_array contour_range = (rel_min, rel_max) contour_order, c_lines = _get_contour_order_and_lines(contour_range) print 'plot range: {: .2f}--{:.2f}'.format( rel_min, rel_max) im = ax.imshow( eff_array, origin = 'upper', extent = (x_min,x_max, y_min, y_max), aspect = aspect, interpolation = 'nearest', vmin = rel_min, vmax = rel_max, ) if len(c_lines) == 0: do_contour = False if do_contour or do_abs_contour: ct = ax.contour( contour_array, origin = 'upper', extent = (x_min,x_max, y_min, y_max), aspect = aspect, linewidths = 2, levels = c_lines, colors = 'k', ) plt.clabel(ct, fontsize=12, inline=1, fmt = '%.{}f'.format(-contour_order + 1 )) equal_contour_level = 1.0 if do_rel else 0.0 if do_equal_contour: equal_ct = ax.contour( eff_array, origin = 'upper', extent = (x_min,x_max, y_min, y_max), aspect = aspect, linewidths = 2, levels = [equal_contour_level], colors = 'r', ) plt.clabel(equal_ct, fontsize=9, inline=True, fmt={equal_contour_level:'equal'}) im.get_cmap().set_bad(alpha=0) ax.set_xticks([]) ax.set_yticks([]) ax.invert_yaxis() cb_ax = plt.subplot(gs[:,-1]) plt.subplots_adjust(left = 0.25) # FIXME: use OO call here # cb = plt.colorbar() cb = Colorbar(ax = cb_ax, mappable = im) taggers = [_simplify_tagger_name(x) for x in arrays] flav_char = _flav_to_char[array_one['signal']] sig_label = '$\epsilon_\mathrm{{ {} }}$'.format(flav_char) cb_lab_string = '{} $/$ {} {s}' if do_rel else '{} $-$ {} {s}' cb.set_label(cb_lab_string.format(*taggers, s = sig_label )) if do_contour: cb.add_lines(ct) if do_equal_contour: if rel_min < equal_contour_level < rel_max: cb.add_lines(equal_ct) position = ax.get_position() new_aspect = ax.get_aspect() # ax.set_position(position) ax_log = fig.add_subplot(111, frameon = False) ax_log.set_xscale('log') ax_log.set_yscale('log') ax_log.axis((10**x_min, 10**x_max, 10**y_min, 10**y_max)) ax_log.set_aspect(aspect) ax_log.set_xlabel('{} rejection'.format(array_one['x_bg'])) ax_log.set_ylabel('{} rejection'.format(array_one['y_bg'])) ax_log.grid(True) cuts_to_display = array_one['cuts_to_display'] for cut in extra_cuts: cut.point_type = 'wo' cuts_to_display.append(cut) for cut in cuts_to_display: x, y, z = cut.xyz # print cut.xyz ax_log.plot([x],[y],cut.point_type) fmt_dict = dict(cut1=cut.cut1, cut2=cut.cut2, eff=z) ax_log.annotate(cut.plot_string.format(**fmt_dict), (x,y), **cut.ann_opts) ax_log.set_aspect(new_aspect) ax_log.set_position(position) plt.savefig(out_name, bbox_inches = 'tight') plt.close()
def add_ortho(lats, lons, colors, CClim, central_longitude, central_latitude, text=None, size=50, marker=['o', 'd'], colormap='viridis', fig=None, rect=[0.0, 0.0, 1.0, 1.0]): if not fig: fig = plt.figure() proj = ccrs.Orthographic(central_longitude=central_longitude, central_latitude=central_latitude) # left, bottom, width, height ax = fig.add_axes([rect[0], rect[1] + rect[3] * 0.12, rect[2], rect[3] * 0.85], projection=proj) cm_ax = fig.add_axes([rect[0], rect[1], rect[2], rect[3] * 0.08]) plt.sca(ax) # make the map global rather than have it zoom in to # the extents of any plotted data ax.set_global() ax.stock_img() ax.coastlines() ax.gridlines() lats_mark1 = [] lons_mark1 = [] colors_mark1 = [] lats_mark2 = [] lons_mark2 = [] colors_mark2 = [] cmap = get_cmap(colormap) cmap.set_under('grey') for lon, lat, color in zip(lons, lats, colors): if color > CClim: lats_mark1.append(lat) lons_mark1.append(lon) colors_mark1.append(color) else: lats_mark2.append(lat) lons_mark2.append(lon) colors_mark2.append(color) if len(lons_mark1) > 0: scatter = ax.scatter(lons_mark1, lats_mark1, s=size, c=colors_mark1, marker=marker[0], cmap=cmap, vmin=CClim, vmax=1, zorder=10, transform=ccrs.Geodetic()) if len(lons_mark2) > 0: scatter = ax.scatter(lons_mark2, lats_mark2, s=size, c=colors_mark2, marker=marker[1], cmap=cmap, vmin=CClim, vmax=1, zorder=10, transform=ccrs.Geodetic()) locator = MaxNLocator(5) cb = Colorbar(cm_ax, scatter, cmap=cmap, orientation='horizontal', ticks=locator, extend='min') cb.set_label('CC') # Compat with old matplotlib versions. if hasattr(cb, "update_ticks"): cb.update_ticks() ax.plot(central_longitude, central_latitude, color='red', marker='*', markersize=np.sqrt(size)) if (text): for lat, lon, text in zip(lats, lons, text): # Avoid plotting invisible texts. They clutter at the origin # otherwise dist = locations2degrees(lat, lon, central_latitude, central_longitude) if (dist < 90): plt.text(lon, lat, text, weight="heavy", transform=ccrs.Geodetic(), color="k", zorder=100, path_effects=[ PathEffects.withStroke(linewidth=3, foreground="white")]) return ax
def AnimateDiameterAndRawData_Big2(rawframes, static_background, rawframes_pre, sizes_df_lin, traj, ParameterJsonFile): from matplotlib.gridspec import GridSpec settings = nd.handle_data.ReadJson(ParameterJsonFile) fps = settings["Exp"]["fps"] my_gamma = settings["Animation"]["gamma"] microns_per_pixel = settings["Exp"]["Microns_per_pixel"] frames_tot = settings["Animation"]["frames_tot"] num_points_pdf = 100 # Diameter plot histogramm_min = settings["Plot"]["Histogramm_min"] histogramm_max = settings["Plot"]["Histogramm_max"] diam_grid = np.linspace(histogramm_min, histogramm_max, 1000) diam_grid_inv = 1 / diam_grid # here comes the font sizes global my_font_size my_font_size = 16 my_font_size_title = 22 global prob_inv_diam_sum prob_inv_diam_sum = np.zeros(num_points_pdf) # get min and max particle id part_id_min = np.min(traj.particle) part_id_max = np.max(traj.particle) # get min and max diameter diam_max = np.round(np.max(sizes_df_lin.diameter) + 5, -1) diam_min = np.round(np.min(sizes_df_lin.diameter) - 5, -1) # get particle id of TRAJECTORIES in the roi # particle_id_traj = traj[(traj.x > 800) & (traj.x < 1800)].particle.unique() particle_id_traj = traj.particle.unique() #get traj in ROI traj_roi = traj[np.isin(traj.particle, particle_id_traj)] frame = 0 # get trajectory of particles in current frame traj_roi_history = GetTrajHistory(frame, traj_roi) # get position and diameter of evaluated particles pos_roi, sizes_df_lin_frame = GetPosEvaluated(frame, traj_roi, sizes_df_lin) # design the subplot fig = plt.figure(figsize=[25, 13], constrained_layout=True) # gs = GridSpec(6, 3, figure=fig, width_ratios = [0.5,0.5,0.2]) gs = GridSpec(12, 5, figure=fig, width_ratios=[1] * 2 + [0.15] * 3, height_ratios=[1 / 2] * (2 * 3) + [1] * 2 + [1.5] + [0.5] * 3) ax_raw = fig.add_subplot(gs[0:2, 0:2], aspect="equal") # raw image ax_bg = fig.add_subplot(gs[2:4, 0:2], aspect="equal", sharex=ax_raw, sharey=ax_raw) # background ax_pp = fig.add_subplot(gs[4:6, 0:2], aspect="equal", sharex=ax_raw, sharey=ax_raw) # post-processed image ax_traj = fig.add_subplot(gs[6, 0:2], aspect="equal", sharex=ax_raw, sharey=ax_raw) # trajectories ax_eval = fig.add_subplot(gs[7, 0:2], aspect="equal", sharex=ax_raw, sharey=ax_raw) # particles colour in diameter ax_hist = fig.add_subplot(gs[8, 0]) # histogram of current frame ax_hist_cum = fig.add_subplot(gs[8, 1], sharex=ax_hist, sharey=ax_hist) # summed histogram # axis for the colorbars / legends c_ax_raw = plt.subplot(gs[0, 2:5]) c_ax_bg = plt.subplot(gs[2, 2:5]) c_ax_pp = plt.subplot(gs[4, 2:5]) c_ax_traj = plt.subplot(gs[6, 2:5]) c_ax_eval = plt.subplot(gs[7, 2:5]) # axis for min, max and gamma values ax_raw_min = plt.subplot(gs[1, 2]) ax_raw_max = plt.subplot(gs[1, 3]) ax_raw_g = plt.subplot(gs[1, 4]) ax_bg_min = plt.subplot(gs[3, 2]) ax_bg_max = plt.subplot(gs[3, 3]) ax_bg_g = plt.subplot(gs[3, 4]) ax_pp_min = plt.subplot(gs[5, 2]) ax_pp_max = plt.subplot(gs[5, 3]) ax_pp_g = plt.subplot(gs[5, 4]) #here come the sliders slider_frame_ax = plt.subplot(gs[9, 0:2]) slider_x_min_ax = plt.subplot(gs[10, 0]) slider_x_max_ax = plt.subplot(gs[11, 0]) slider_y_min_ax = plt.subplot(gs[10, 1]) slider_y_max_ax = plt.subplot(gs[11, 1]) # plot the stuff import matplotlib.colors as colors raw_image = ax_raw.imshow(rawframes[0, :, :], cmap='gray', norm=colors.PowerNorm(gamma=my_gamma), animated=True, vmin=0, vmax=np.max(rawframes)) bg_image = ax_bg.imshow(static_background, cmap='gray', norm=colors.PowerNorm(gamma=my_gamma), animated=True, vmin=0, vmax=np.max(static_background)) pp_image = ax_pp.imshow(rawframes_pre[0, :, :], cmap='gray', norm=colors.PowerNorm(gamma=my_gamma), animated=True, vmin=np.min(rawframes_pre), vmax=np.max(rawframes_pre)) ax_scatter_traj = ax_traj.scatter(traj_roi_history.x, traj_roi_history.y, s=3, c=traj_roi_history.particle, cmap='gist_ncar', alpha=1, vmin=0, vmax=part_id_max) # ax_scatter_traj = ax_traj.scatter(traj_roi_history.x, traj_roi_history.y, s = 3, c = traj_roi_history.particle, cmap = 'gist_ncar', alpha = 1, vmin=part_id_min, vmax=part_id_max) ax_scatter_diam = ax_eval.scatter(pos_roi.x, pos_roi.y, c=sizes_df_lin_frame.diameter, cmap='gist_ncar', vmin=diam_min, vmax=diam_max) # add titles and labels ax_raw.set_title('raw-data', fontsize=my_font_size_title) ax_raw.set_ylabel('y-Position [px]', fontsize=my_font_size) ax_bg.set_title('Background and stationary particles', fontsize=my_font_size_title) ax_bg.set_ylabel('y-Position [px]', fontsize=my_font_size) ax_pp.set_title('Processed image', fontsize=my_font_size_title) ax_pp.set_ylabel('y-Position [px]', fontsize=my_font_size) ax_traj.set_title('trajectory', fontsize=my_font_size_title) ax_traj.set_ylabel('y-Position [px]', fontsize=my_font_size) ax_eval.set_title('Diameter of each particle', fontsize=my_font_size_title) ax_eval.set_ylabel('y-Position [px]', fontsize=my_font_size) ax_eval.set_xlabel('x-Position [px]', fontsize=my_font_size) # COLORBARS from matplotlib.colorbar import Colorbar cb_raw = Colorbar(ax=c_ax_raw, mappable=raw_image, orientation='horizontal', ticklocation='top') cb_raw.set_label("Brightness", fontsize=my_font_size) cb_bg = Colorbar(ax=c_ax_bg, mappable=bg_image, orientation='horizontal', ticklocation='top') cb_bg.set_label("Brightness", fontsize=my_font_size) cb_pp = Colorbar(ax=c_ax_pp, mappable=pp_image, orientation='horizontal', ticklocation='top') cb_pp.set_label("Brightness", fontsize=my_font_size) cb_traj = Colorbar(ax=c_ax_traj, mappable=ax_scatter_traj, orientation='horizontal', ticklocation='top') cb_traj.set_label("Particle ID", fontsize=my_font_size) cb_eval = Colorbar(ax=c_ax_eval, mappable=ax_scatter_diam, orientation='horizontal', ticklocation='top') cb_eval.set_label("Diameter [nm]", fontsize=my_font_size) from matplotlib import ticker cb_raw.locator = ticker.MaxNLocator(nbins=3) cb_raw.update_ticks() cb_bg.locator = ticker.MaxNLocator(nbins=3) cb_bg.update_ticks() cb_pp.locator = ticker.MaxNLocator(nbins=3) cb_pp.update_ticks() cb_traj.locator = ticker.MaxNLocator(nbins=5) cb_traj.update_ticks() cb_eval.locator = ticker.MaxNLocator(nbins=5) cb_eval.update_ticks() # Here come the two histograms line_diam_frame, = ax_hist.plot(diam_grid, np.zeros_like(diam_grid)) line_diam_sum, = ax_hist_cum.plot(diam_grid, np.zeros_like(diam_grid)) # label and title ax_hist.set_xlabel('Diameter [nm]', fontsize=my_font_size) ax_hist.set_ylabel('Occurance', fontsize=my_font_size) ax_hist.set_title("Live Histogram", fontsize=my_font_size_title) ax_hist_cum.set_xlabel('Diameter [nm]', fontsize=my_font_size) ax_hist_cum.set_ylabel('Occurance', fontsize=my_font_size) ax_hist_cum.set_title("Cummulated Histogram", fontsize=my_font_size_title) # limits ax_hist.set_xlim([histogramm_min, histogramm_max]) ax_hist.set_ylim([0, 1.1]) ax_hist.set_yticks([]) ax_hist.tick_params(direction='out') # Global PDF inv_diam, inv_diam_std = nd.CalcDiameter.InvDiameter( sizes_df_lin, settings) prob_inv_diam = np.zeros_like(diam_grid_inv) for index, (loop_mean, loop_std, weight) in enumerate( zip(inv_diam, inv_diam_std, sizes_df_lin["traj length"])): #loop through all evaluated partices in that roi and frame #calc probability density function (PDF) my_pdf = scipy.stats.norm(loop_mean, loop_std).pdf(diam_grid_inv) # normalized nad weight my_pdf = my_pdf / np.sum(my_pdf) * weight #add up all PDFs prob_inv_diam = prob_inv_diam + my_pdf #normalized to 1 prob_inv_diam_show = prob_inv_diam / np.max(prob_inv_diam) line_diam_sum.set_ydata(prob_inv_diam_show) def animate(frame, x_min, x_max, y_min, y_max, UpdateFrame): global ColorbarDone print("\nframe", frame) print("x_min", x_min) print("x_max", x_max) print("y_min", y_min) print("y_max", y_max) print("Update Frame", UpdateFrame) # select new frame if required if UpdateFrame == True: rawframes_frame = rawframes[frame, :, :] rawframes_pp_frame = rawframes_pre[frame, :, :] raw_image.set_data(rawframes_frame) bg_image.set_data(static_background) pp_image.set_data(rawframes_pp_frame) # SET AXES ax_raw.set_xlim([x_min, x_max]) ax_raw.set_ylim([y_min, y_max]) ax_raw.tick_params(direction='out') # make the labels in um num_x_ticks = 5 num_y_ticks = 3 x_ticks_px = np.round( np.linspace(x_min, x_max, num_x_ticks, dtype='int'), -2) y_ticks_px = np.round( np.linspace(y_min, y_max, num_y_ticks, dtype='int'), -1) ax_raw.set_xticks(x_ticks_px) ax_raw.set_xticklabels(x_ticks_px) ax_raw.set_yticks(y_ticks_px) ax_raw.set_yticklabels(y_ticks_px) # get particle id of TRAJECTORIES in the roi particle_id_traj = traj[(traj.x > x_min) & (traj.x < x_max)].particle.unique() #get traj in ROI traj_roi = traj[traj.particle.isin(particle_id_traj)] # get trajectory of particles in current frame traj_roi_history = GetTrajHistory(frame, traj_roi) # get position and diameter of evaluated particles pos_roi, sizes_df_lin_roi_frame = GetPosEvaluated( frame, traj_roi, sizes_df_lin) #update figure time_ms = frame * (1 / fps) * 1000 time_ms = np.round(time_ms, 1) fig.suptitle('frame: ' + str(frame) + '; time: ' + str(time_ms) + ' ms', fontsize=my_font_size_title) ax_scatter_traj.set_offsets( np.transpose( np.asarray( [traj_roi_history.x.values, traj_roi_history.y.values]))) ax_scatter_traj.set_array(traj_roi_history.particle) ax_scatter_diam.set_offsets( np.transpose(np.asarray([pos_roi.x.values, pos_roi.y.values]))) ax_scatter_diam.set_array(sizes_df_lin_roi_frame.diameter) ## DIAMETER PDF FROM PREVIOUS POINTS sizes_df_lin_roi_frame = sizes_df_lin_roi_frame.sort_index() # get inverse diameter which is normal distributed (proportional to the diffusion) inv_diam, inv_diam_std = nd.CalcDiameter.InvDiameter( sizes_df_lin_roi_frame, settings) # probability of inverse diameter prob_inv_diam = np.zeros_like(diam_grid_inv) for index, (loop_mean, loop_std) in enumerate(zip(inv_diam, inv_diam_std)): #loop through all evaluated partices in that roi and frame #calc probability density function (PDF) my_pdf = scipy.stats.norm(loop_mean, loop_std).pdf(diam_grid_inv) # normalized my_pdf = my_pdf / np.sum(my_pdf) #add up all PDFs prob_inv_diam = prob_inv_diam + my_pdf #normalized to 1 if np.max(prob_inv_diam) > 0: prob_inv_diam_show = prob_inv_diam / np.max(prob_inv_diam) else: prob_inv_diam_show = prob_inv_diam line_diam_frame.set_ydata(prob_inv_diam_show) # # # # ## ACCUMULATED DIAMETER PDF # #normalized to 1 # prob_inv_diam_sum_show = prob_inv_diam_sum / np.max(prob_inv_diam_sum) # # line_diam_sum.set_ydata(prob_inv_diam_sum_show) print("Animation updated") return raw_image # Functions for Update the ROI and brightness def UpdateFrame(val): UpdateFrame = True UpdateAnimation(UpdateFrame, val) def UpdateROI(val): UpdateFrame = False UpdateAnimation(UpdateFrame, val) def UpdateAnimation(UpdateROI, val): frame = int(slider_frame.val) x_min = int(slider_x_min.val) x_max = int(slider_x_max.val) y_min = int(slider_y_min.val) y_max = int(slider_y_max.val) animate(frame, x_min, x_max, y_min, y_max, UpdateROI) plt.draw() def UpdateColorbarRawimage(stuff): v_min = np.int(textbox_raw_min.text) v_max = np.int(textbox_raw_max.text) my_gamma = np.double(textbox_raw_g.text) print("\n v_min = ", v_min) print("v_max = ", v_max) print("gamma = ", my_gamma) raw_image.set_norm(colors.PowerNorm(gamma=my_gamma)) raw_image.set_clim([v_min, v_max]) cb_raw = Colorbar(ax=c_ax_raw, mappable=raw_image, orientation='horizontal', ticklocation='top') cb_raw.locator = ticker.MaxNLocator(nbins=3) cb_raw.update_ticks() def UpdateColorbarBg(stuff): v_min = np.int(textbox_bg_min.text) v_max = np.int(textbox_bg_max.text) my_gamma = np.double(textbox_bg_g.text) print("\n v_min = ", v_min) print("v_max = ", v_max) print("gamma = ", my_gamma) bg_image.set_norm(colors.PowerNorm(gamma=my_gamma)) bg_image.set_clim([v_min, v_max]) cb_bg = Colorbar(ax=c_ax_bg, mappable=bg_image, orientation='horizontal', ticklocation='top') cb_bg.locator = ticker.MaxNLocator(nbins=3) cb_bg.update_ticks() def UpdateColorbarPP(stuff): v_min = np.int(textbox_pp_min.text) v_max = np.int(textbox_pp_max.text) my_gamma = np.double(textbox_pp_g.text) print("\n v_min = ", v_min) print("v_max = ", v_max) print("gamma = ", my_gamma) pp_image.set_norm(colors.PowerNorm(gamma=my_gamma)) pp_image.set_clim([v_min, v_max]) cb_pp = Colorbar(ax=c_ax_pp, mappable=pp_image, orientation='horizontal', ticklocation='top') cb_pp.locator = ticker.MaxNLocator(nbins=3) cb_pp.update_ticks() # anim = animation.FuncAnimation(fig, animate, init_func=init, frames = 100, interval=100, blit=True, repeat=False) # anim = animation.FuncAnimation(fig, animate, frames = 1000, interval = 10, repeat = False) min_frame = int(traj_roi.frame.min()) max_frame = int(traj_roi.frame.max()) show_frames = np.linspace(min_frame, max_frame, frames_tot, dtype='int') Do_Save = True # HERE COME THE TEXTBOXES AND SLIDERS from matplotlib.widgets import Slider, Button, TextBox #raw image textbox_raw_min = TextBox(ax_raw_min, "min: ", initial=str(np.min(rawframes[0, :, :])), hovercolor="y") textbox_raw_min.on_submit(UpdateColorbarRawimage) textbox_raw_max = TextBox(ax_raw_max, "max: ", initial=str(np.max(rawframes[0, :, :])), hovercolor="y") textbox_raw_max.on_submit(UpdateColorbarRawimage) textbox_raw_g = TextBox(ax_raw_g, "gamma: ", initial=str(my_gamma), hovercolor="y") textbox_raw_g.on_submit(UpdateColorbarRawimage) #bg textbox_bg_min = TextBox(ax_bg_min, "min: ", initial=str(np.int(np.min(static_background))), hovercolor="y") textbox_bg_min.on_submit(UpdateColorbarBg) textbox_bg_max = TextBox(ax_bg_max, "max: ", initial=str(np.int(np.max(static_background))), hovercolor="y") textbox_bg_max.on_submit(UpdateColorbarBg) textbox_bg_g = TextBox(ax_bg_g, "gamma: ", initial=str(my_gamma), hovercolor="y") textbox_bg_g.on_submit(UpdateColorbarBg) #preproccesd (pp) textbox_pp_min = TextBox(ax_pp_min, "min: ", initial=str(np.int(np.min( rawframes_pre[0, :, :]))), hovercolor="y") textbox_pp_min.on_submit(UpdateColorbarPP) textbox_pp_max = TextBox(ax_pp_max, "max: ", initial=str(np.int(np.max( rawframes_pre[0, :, :]))), hovercolor="y") textbox_pp_max.on_submit(UpdateColorbarPP) textbox_pp_g = TextBox(ax_pp_g, "gamma: ", initial=str(my_gamma), hovercolor="y") textbox_pp_g.on_submit(UpdateColorbarPP) # sliders frame_max = rawframes.shape[0] - 1 x_max_max = rawframes.shape[2] - 1 y_max_max = rawframes.shape[1] - 1 slider_frame = Slider(slider_frame_ax, "Frame: ", valmin=0, valmax=frame_max, valinit=0, valstep=1) slider_x_min = Slider(slider_x_min_ax, "x_min: ", valmin=0, valmax=x_max_max, valinit=0, valstep=1) slider_x_max = Slider(slider_x_max_ax, "x_max: ", valmin=0, valmax=x_max_max, valinit=x_max_max, valstep=1, slidermin=slider_x_min) slider_y_min = Slider(slider_y_min_ax, "y_min: ", valmin=0, valmax=y_max_max, valinit=0, valstep=1) slider_y_max = Slider(slider_y_max_ax, "y_max: ", valmin=0, valmax=y_max_max, valinit=y_max_max, valstep=1, slidermin=slider_y_min) slider_frame.on_changed(UpdateFrame) slider_x_min.on_changed(UpdateROI) slider_x_max.on_changed(UpdateROI) slider_y_min.on_changed(UpdateROI) slider_y_max.on_changed(UpdateROI) plt.show() # if Do_Save == True: # anim = animation.FuncAnimation(fig, animate, frames = show_frames, init_func=init, interval = 0, repeat = False) # anim.save('200204_2.html', writer = 'html', fps=1) # # else: # anim = animation.FuncAnimation(fig, animate, frames = show_frames, init_func=init, interval = 5, repeat = True) # return anim return
'35 km', fontsize=fontsize, ha='center', va='center') #deal with colorbars if ((filenum == 1) & (i == 0)): # plot first color bar in row 1 colorax = plt.subplot(gs[1, rowscale]) colorbar1 = Colorbar(ax=colorax, mappable=cs, orientation='horizontal', ticklocation='bottom', ticks=[0.2, 0.5, 0.8]) colorbar1.ax.tick_params(labelsize=fontsize) clabel = '$\mathrm{sig}(\mathrm{a}\Delta \mathrm{CFS}-\mathrm{b})$' colorbar1.set_label(clabel, size=fontsize) pos = colorax.get_position() # get the original position colorax.set_position( [pos.x0, pos.y0 + 0.017, pos.width, pos.height]) if ((filenum == 1) & (i == 1)): # plot first color bar in row 3 colorax = plt.subplot(gs[i * 2 + 1, filenum * rowscale]) colorbar2 = Colorbar(ax=colorax, mappable=cs, orientation='horizontal', ticklocation='bottom', ticks=[0.2, 0.5, 0.8]) colorbar2.ax.tick_params(labelsize=fontsize) colorbar2.set_label('$\mathrm{NN}\,\mathrm{output}$', size=fontsize) pos = colorax.get_position() # get the original position colorax.set_position([pos.x0, pos.y0, pos.width, pos.height])
lw=0.8, alpha=0.7) # Archimedean spiral model ax.plot(Rsp[tbins_sp <= 180], tbins_sp[tbins_sp <= 180], '--y', alpha=0.7) ax.plot(Rsp[tbins_sp > 180], tbins_sp[tbins_sp > 180] - 360, '--y', alpha=0.7) # limits and labeling ax.set_xlim(rlims) ax.set_ylim(tlims) ax.set_yticks([-180, -90, 0, 90, 180]) ax.set_xlabel('radius ($^{\prime\prime}$)', labelpad=3) ax.set_ylabel('azimuth ($^\circ$)', labelpad=-1.5) ax.tick_params(axis='y', length=2.5) ax.tick_params(axis='x', length=2.5) # colorbar cbax = fig.add_axes([left, top + 0.01, right - left, 0.02]) cb = Colorbar(ax=cbax, mappable=im, orientation='horizontal', ticklocation='top') cbax.tick_params('both', length=2, direction='out', which='major') cb.set_label('residual ($\\mu$Jy / bm)', labelpad=4) # Configure plots fig.subplots_adjust(wspace=wspace, hspace=hspace) fig.subplots_adjust(left=left, right=right, bottom=bottom, top=top) fig.savefig('../figs/HD143006_spiral.pdf') fig.clf()
#DRAW ARROW POINTING TO AXIS for i in [2, 3]: axarr[i].annotate(s='Snapshot\nbelow', xy=(period / len(datevec), 0), xytext=(period / len(datevec) - .125, -.3), xycoords='axes fraction', arrowprops=dict(facecolor='red', shrink=0.05), annotation_clip=False, fontsize=ftsz - 4) #COLORBAR from matplotlib.colorbar import Colorbar cbar_ax2 = plt.subplot(gs[-1, -1]) cbar2 = Colorbar(ax=cbar_ax2, mappable=image, orientation="vertical") cbar2.set_label('Soil Moisture (cm$^3$/cm$^3$)', fontsize=ftsz) #POINTS for idx in range(len(alllatlocations)): lat_in = lat[int(alllatlocations[idx] + 331), 0] lon_in = lon[0, int(alllonlocations[idx] + 1097)] dot = m.plot(lon_in, lat_in, markeredgecolor='r', markerfacecolor='lime', markeredgewidth=0.75, marker='D', markersize=3) offset = (-15, -15) axarr[4].axvline((94.5 + 120) / 2, color='grey', linestyle='--', linewidth=1.5)
def add_ortho(lats, lons, colors, CClim, central_longitude, central_latitude, text=None, size=50, marker=['o', 'd'], colormap='viridis', fig=None, rect=[0.0, 0.0, 1.0, 1.0]): if not fig: fig = plt.figure() proj = ccrs.Orthographic(central_longitude=central_longitude, central_latitude=central_latitude) # left, bottom, width, height ax = fig.add_axes( [rect[0], rect[1] + rect[3] * 0.12, rect[2], rect[3] * 0.85], projection=proj) cm_ax = fig.add_axes([rect[0], rect[1], rect[2], rect[3] * 0.08]) plt.sca(ax) # make the map global rather than have it zoom in to # the extents of any plotted data ax.set_global() ax.stock_img() ax.coastlines() ax.gridlines() lats_mark1 = [] lons_mark1 = [] colors_mark1 = [] lats_mark2 = [] lons_mark2 = [] colors_mark2 = [] cmap = get_cmap(colormap) cmap.set_under('grey') for lon, lat, color in zip(lons, lats, colors): if color > CClim: lats_mark1.append(lat) lons_mark1.append(lon) colors_mark1.append(color) else: lats_mark2.append(lat) lons_mark2.append(lon) colors_mark2.append(color) if len(lons_mark1) > 0: scatter = ax.scatter(lons_mark1, lats_mark1, s=size, c=colors_mark1, marker=marker[0], cmap=cmap, vmin=CClim, vmax=1, zorder=10, transform=ccrs.Geodetic()) if len(lons_mark2) > 0: scatter = ax.scatter(lons_mark2, lats_mark2, s=size, c=colors_mark2, marker=marker[1], cmap=cmap, vmin=CClim, vmax=1, zorder=10, transform=ccrs.Geodetic()) locator = MaxNLocator(5) cb = Colorbar(cm_ax, scatter, cmap=cmap, orientation='horizontal', ticks=locator, extend='min') cb.set_label('CC') # Compat with old matplotlib versions. if hasattr(cb, "update_ticks"): cb.update_ticks() ax.plot(central_longitude, central_latitude, color='red', marker='*', markersize=np.sqrt(size)) if (text): for lat, lon, text in zip(lats, lons, text): # Avoid plotting invisible texts. They clutter at the origin # otherwise dist = locations2degrees(lat, lon, central_latitude, central_longitude) if (dist < 90): plt.text(lon, lat, text, weight="heavy", transform=ccrs.Geodetic(), color="k", zorder=100, path_effects=[ PathEffects.withStroke(linewidth=3, foreground="white") ]) return ax
def plot_AcrossASF_woWinds(acASF, dfmg, wd=190 / 25.4, ht=230 / 25.4, savefig=False, savename="untitled.png", levels=[], xlat=False, show=True, MEOPDIR="/media/sda7", p2pdist=True, fontsize=8, region='Whole', bathy=None, plotBathy=True, llcrnrlon=-180, llcrnrlat=-90, urcrnrlon=+180, urcrnrlat=+90): matplotlib.rcParams.update({'font.size': fontsize}) plt.close(1) fig = plt.figure(1, figsize=(wd, ht)) gs = gridspec.GridSpec(3, 2, height_ratios=[1, 0.25, 0.5], width_ratios=[1, 0.02], hspace=0., wspace=0.05) contour_ax = plt.subplot(gs[0, 0]) if (region == "CDP"): llcrnrlon, llcrnrlat = 60, -68 urcrnrlon, urcrnrlat = 71, -65.5 map_proj = ccrs.PlateCarree() #ccrs.Orthographic(65, -90) if (region == "WPB"): llcrnrlon, llcrnrlat = 69, -70 urcrnrlon, urcrnrlat = 80, -66 map_proj = ccrs.PlateCarree() #ccrs.Orthographic(65, -90) if (region == "EPB"): llcrnrlon, llcrnrlat = 69, -70 urcrnrlon, urcrnrlat = 83, -64.5 map_proj = ccrs.PlateCarree() #ccrs.Orthographic(65, -90) if (region == "LAC"): llcrnrlon, llcrnrlat = 80, -68 urcrnrlon, urcrnrlat = 89, -64.5 map_proj = ccrs.PlateCarree() #ccrs.Orthographic(65, -90) if (region == "KC"): llcrnrlon, llcrnrlat = 99, -68 urcrnrlon, urcrnrlat = 112, -63 map_proj = ccrs.PlateCarree() #ccrs.Orthographic(65, -90) if (region == "AC"): llcrnrlon, llcrnrlat = 133, -68 urcrnrlon, urcrnrlat = 147, -64 map_proj = ccrs.PlateCarree() #ccrs.Orthographic(65, -90) if (region == "RS"): llcrnrlon, llcrnrlat = 160, -79 urcrnrlon, urcrnrlat = 180, -71 map_proj = ccrs.PlateCarree() #ccrs.Orthographic(65, -90) if (region == "AS"): llcrnrlon, llcrnrlat = -122, -75.5 urcrnrlon, urcrnrlat = -98, -70 map_proj = ccrs.PlateCarree() #ccrs.Orthographic(65, -90) if (region == "BS"): llcrnrlon, llcrnrlat = -102, -71.5 urcrnrlon, urcrnrlat = -58, -60 map_proj = ccrs.PlateCarree() #ccrs.Orthographic(65, -90) if (region == "WS"): llcrnrlon, llcrnrlat = -50, -82 urcrnrlon, urcrnrlat = -20, -72 map_proj = ccrs.PlateCarree() #ccrs.Orthographic(65, -90) if (region == "PMC"): llcrnrlon, llcrnrlat = -19, -74 urcrnrlon, urcrnrlat = 0, -65 map_proj = ccrs.PlateCarree() #ccrs.Orthographic(65, -90) if (region == "PHC"): llcrnrlon, llcrnrlat = 28, -71 urcrnrlon, urcrnrlat = 38, -65 map_proj = ccrs.PlateCarree() #ccrs.Orthographic(65, -90) else: map_proj = ccrs.PlateCarree() mapax = plt.subplot(gs[2, 0], projection=map_proj) mapax.set_extent([llcrnrlon, urcrnrlon, llcrnrlat, urcrnrlat], crs=ccrs.PlateCarree()) colorbar_ax1 = plt.subplot(gs[0, 1]) colorbar_ax2 = plt.subplot(gs[2, 1]) profs = acASF.PROFILE_NUMBERS profs = [int(x) for x in profs.split(',')] year = dfmg.loc[dfmg.PROFILE_NUMBER.isin([profs[0]]), "JULD"].dt.year.values[0] month = dfmg.loc[dfmg.PROFILE_NUMBER.isin([profs[0]]), "JULD"].dt.month.values[0] region = acASF.REGION ctemps = [] latlons = [] depth = [] gamman = [] echodepth = [] dist_gline = [] zonal = [] merid = [] stress_curl = [] wek = [] no_of_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] for i in range(len(profs)): dfSelect = dfmg.PROFILE_NUMBER.isin([profs[i]]) ctemps = np.concatenate((ctemps, dfmg.loc[dfSelect, "CTEMP"].values)) latlons.append([ dfmg.loc[dfSelect, 'LATITUDE'].values[0], dfmg.loc[dfSelect, 'LONGITUDE'].values[0] ]) depth = np.concatenate((depth, dfmg.loc[dfSelect, "DEPTH"].values)) gamman = np.concatenate((gamman, dfmg.loc[dfSelect, "gamman"].values)) echodepth = np.concatenate( (echodepth, [dfmg.loc[dfSelect].ECHODEPTH.values[0]])) if xlat: dist_gline = np.concatenate( (dist_gline, dfmg.loc[dfSelect, "LATITUDE"].values)) elif p2pdist: if (i == 0): dist_gline = np.concatenate( (dist_gline, np.zeros(len(dfmg[dfSelect])))) else: dist = dist_gline[-1] + haversine(latlons[i - 1], latlons[i]) dist_gline = np.concatenate( (dist_gline, np.zeros(len(dfmg[dfSelect]), dtype=float) + dist)) else: dist_gline = np.concatenate( (dist_gline, dfmg.loc[dfSelect, "DIST_GLINE"].values)) latlons = np.array(latlons) dist_echo = np.unique(dist_gline) print(gamman.shape) if xlat: ndist = int(np.max(dist_gline) / 0.1) else: ndist = int(np.max(dist_gline) / 2.) dist_grid = np.linspace(np.min(dist_gline), np.max(dist_gline), ndist) ndepth = int(-np.min(depth) / 10.) depth_grid = np.linspace(np.min(depth), 0, ndepth) dist_grid, depth_grid = np.meshgrid(dist_grid, depth_grid) gamman_interpolated = griddata(np.array([dist_gline, depth]).T, gamman, (dist_grid, depth_grid), method='cubic') cs = contour_ax.scatter(dist_gline, depth, c=ctemps, vmin=-2.0, vmax=0.5, s=10) slope_labels = np.zeros(len(echodepth), dtype=int) slope_labels[echodepth > -1000] = 0 slope_labels[(echodepth < -1000) & (echodepth > -1500)] = 1 slope_labels[(echodepth < -1500) & (echodepth > -2000)] = 2 slope_labels[(echodepth < -2000) & (echodepth > -3000)] = 3 slope_labels[(echodepth < -3000)] = 4 contour_ax_twinx = contour_ax.twiny() contour_ax_twinx.set_xticks(dist_echo) contour_ax_twinx.set_xticklabels(slope_labels) contour_ax.set_ylabel("Depth (m)") if xlat: contour_ax.set_xlabel("Latitude") elif p2pdist: contour_ax.set_xlabel("Chainage (km)") else: contour_ax.set_xlabel("Distance from GL (km)") xaxislength = np.max(dist_gline) - np.min(dist_gline) contour_ax.set_xlim( np.min(dist_gline) - xaxislength * 0.02, np.max(dist_gline) + xaxislength * 0.02) contour_ax_twinx.set_xlim( np.min(dist_gline) - xaxislength * 0.02, np.max(dist_gline) + xaxislength * 0.02) if levels: cs_gamman = contour_ax.contour(dist_grid, depth_grid, gamman_interpolated, levels=levels, colors='0.5') else: try: levels = np.array(str.split(acASF.LEVELS, ","), dtype=float) cs_gamman = contour_ax.contour(dist_grid, depth_grid, gamman_interpolated, levels=levels, colors='0.5') except: levels = None cs_gamman = contour_ax.contour(dist_grid, depth_grid, gamman_interpolated, colors='0.5') contour_ax.clabel(cs_gamman, colors='k', fontsize=8, fmt='%3.2f') #mapax.plot(latlons.LONGITUDE.values, latlons.LATITUDE.values, marker="x", markersize=20, transform=ccrs.PlateCarree() ) mapax.scatter(latlons[:, 1], latlons[:, 0], marker="x", s=20, transform=ccrs.PlateCarree()) #mapax.coastlines() parallels = np.arange(-80, -50 + 1, 5.) #m.drawparallels(parallels,labels=[1,0,0,0], linewidth=0.2, ax=mapax) # labels: left,right,top,bottom meridians = np.arange(-180, 180, 20.) #m.drawmeridians(meridians,labels=[0,1,1,1], linewidth=0.2, ax=mapax) cbar1 = Colorbar(ax=colorbar_ax1, mappable=cs, orientation='vertical', extend='both', label="CT$^\circ$C") if (plotBathy == True): try: if bathy.variables: pass except: bathy = xr.open_dataset(MEOPDIR + '/Datasets/Bathymetry/GEBCO_2014_2D.nc') lonlen = len(bathy.lon) lonindices = np.arange(0, lonlen + 1, 30) lonindices[-1] = lonindices[-1] - 1 bathyS = bathy.isel(lon=lonindices, lat=np.arange(0, 3600, 5)) clevs = np.array([-1000, -1500, -2000, -3000])[::-1] longrid, latgrid = np.meshgrid(bathyS.lon.values, bathyS.lat.values) cs2 = mapax.contour( longrid, latgrid, bathyS.elevation.where(bathyS.elevation <= 0).values, levels=clevs, linewidths=0.8, transform=ccrs.PlateCarree( )) #, , cmap='rainbow' , levels=clevs, ## plt.figure(2) ## cf = plt.contourf(longrid, latgrid,bathyS.elevation.where(bathyS.elevation <= 0).values, levels=clevs, extend='min') #, , cmap='rainbow' , levels=clevs, ## plt.figure(1) cbar1 = Colorbar(ax=colorbar_ax2, mappable=cs2, orientation='vertical') cbar1.ax.get_children()[0].set_linewidths(5) cbar1.set_label('Depth (m)') shpfile = MEOPDIR + "/Datasets/Shapefiles/AntarcticGroundingLine/GSHHS_f_L6.shp" with fiona.open(shpfile) as records: geometries = [sgeom.shape(shp['geometry']) for shp in records] mapax.add_geometries(geometries, ccrs.PlateCarree(), edgecolor='k', facecolor='none') ISedgefname = MEOPDIR + "/Datasets/Shapefiles/AntIceShelfEdge/ne_10m_antarctic_ice_shelves_lines.shp" ISe_feature = ShapelyFeature(Reader(ISedgefname).geometries(), ccrs.PlateCarree(), facecolor='none', edgecolor="gray") mapax.add_feature(ISe_feature, zorder=3) mapax.set_extent([llcrnrlon, urcrnrlon, llcrnrlat, urcrnrlat]) gl = mapax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True, linewidth=1, color='gray', alpha=0.5, linestyle='--') gl.ylabels_right = False gl.xlabels_top = False gl.xformatter = LONGITUDE_FORMATTER gl.yformatter = LATITUDE_FORMATTER gl.xlabel_style = {'size': 8, 'color': 'k'} gl.ylabel_style = {'size': 8, 'color': 'k'} gl = contour_ax.grid(linewidth=1, color='gray', alpha=0.5, linestyle='--') contour_ax.set_title(region + ", " + str(year) + "/ " + str(month)) if savefig: plt.savefig(savename, dpi=300, bbox_inches="tight") if show: plt.show()
def plot_grid(ratios, coeffs = [[1,0],[0,1]], Pk = 5.0, kappa=np.inf, struct = 'pp', sampling = 1, color_mode = 'Tot[O]+12', figname = None, show_plot = True, data = None, interp_data = None): ''' Creates the diagram of a given line ratio grid for rapid inspection, including wraps (fold-over regions), and of certain line ratios, if "data" is specified. :Args: ratios: string The line ratios defining the grid, e.g. '[NII]/[SII]+;[OIII]/Hb' coeffs: list of list [default: [[1,0],[0,1]] ] The different coefficients with which to mix the line ratios. The size of each sub-list must be equal to the number of line ratios involved. Used for projected 3D diagnostic grids. Pk: float [default: 5.0] MAPPINGS model pressure. This value must match an existing grid file. kappa: float [default: np.inf The kappa value. This value must match an existing grid file. struct: string [default: 'pp'] spherical ('sph') or plane-parallel ('pp') HII regions. This value must match an existing reference grid file. sampling: int [default: 1] Use a resampled grid ? color_mode: string [default: 'Tot[O]+12'] Color the grid according to 'Tot[O]+12', 'gas[O]+12' or 'LogQ'. figname: string [default: None] 'path+name+format' to save the Figure to. show_plot: bool [default: True] Do you want to display the Figure ? data: list of numpy array [default: None] List of Arrays of the line ratio values. One array per line ratio. interp_data: numpy array [default: 'linear'] interpolated line ratios (via pyqz.interp_qz) ''' # 0) Let's get the data in question [grid, grid_cols, metadata] = pyqz.get_grid(ratios, coeffs=coeffs, Pk=Pk, kappa=kappa, struct=struct, sampling = sampling) # 1) What are the bad segments in this grid ? bad_segs = pyqz.check_grid(ratios, coeffs=coeffs, Pk = Pk, kappa=kappa, struct=struct, sampling = sampling) # 2) Start the plotting fig = plt.figure(figsize=(10,8)) gs = gridspec.GridSpec(1,2, height_ratios=[1], width_ratios=[1,0.05]) gs.update(left=0.14,right=0.88,bottom=0.14,top=0.92, wspace=0.1,hspace=0.1) ax1 = fig.add_subplot(gs[0,0]) if not(color_mode in grid_cols): sys.exit('color_mode unknown: %s' % color_mode) # 2) Plot the grid points # Let's make the distinction between the 'TRUE' MAPPINGS point, # and those that were interpolated in a finer grid using Akima splines pts = ax1.scatter(grid[:,grid_cols.index('Mix_x')], grid[:,grid_cols.index('Mix_y')], marker='o', c=grid[:,grid_cols.index(color_mode)], s=30, cmap=pyqz_cmap_0, edgecolor='none', vmin=np.min(grid[:,grid_cols.index(color_mode)]), vmax=np.max(grid[:,grid_cols.index(color_mode)]), zorder=3) # Now mark the "original" points with a black outline. First, which are they ? if sampling > 1: origin_cond = [n for n in range(len(grid)) if (grid[n,metadata['columns'].index('LogQ')] in metadata['resampled']['LogQ']) and (grid[n,metadata['columns'].index('Tot[O]+12')] in metadata['resampled']['Tot[O]+12'])] else: origin_cond = [n for n in range(len(grid))] # Now plot the black outlines. original_pts = ax1.scatter(grid[origin_cond, grid_cols.index('Mix_x')], grid[origin_cond, grid_cols.index('Mix_y')], marker='o', c=grid[origin_cond, grid_cols.index(color_mode)], s=60, cmap=pyqz_cmap_0, edgecolor='k', facecolor='white', vmin=np.min(grid[:,grid_cols.index(color_mode)]), vmax=np.max(grid[:,grid_cols.index(color_mode)]), zorder=5) # 2-1) Draw the grid lines # Check as a function of LogQ and Tot[O]+12. Where are these ? u = grid_cols.index('LogQ') v = grid_cols.index('Tot[O]+12') for i in [u,v]: # Here, 'var' plays the role of 'q' or 'z' depending on 'i'. for var in np.unique(grid[:,i]): # Plot the grid line ax1.plot(grid[grid[:,i]==var][:,grid_cols.index('Mix_x')], grid[grid[:,i]==var][:,grid_cols.index('Mix_y')], 'k-', lw = 1, zorder=1) # Plot the bad segments for bad_seg in bad_segs: ax1.plot([bad_seg[0][0],bad_seg[1][0]],[bad_seg[0][1],bad_seg[1][1]], 'r-', linewidth=4, zorder=0) # Now, also plot the data, if anything was provided ! if not(interp_data is None): # Compute the combined "observed" ratios data_comb = [np.zeros_like(data[0]),np.zeros_like(data[1])] for k in range(len(ratios.split(';'))): data_comb[0] += coeffs[0][k]*data[k] data_comb[1] += coeffs[1][k]*data[k] ax1.scatter(data_comb[0][interp_data == interp_data], data_comb[1][interp_data == interp_data], marker='s', c=interp_data[interp_data == interp_data], s=15, cmap = pyqz_cmap_0, edgecolor='k', vmin = np.min(grid[:,grid_cols.index(color_mode)]), vmax = np.max(grid[:,grid_cols.index(color_mode)]), zorder=2, alpha=0.35) # Plot also the points outside the grid ? # Which are they ? Need to check if they have a valid input first ! # mind the "~" to invert the bools ! isn't this cool ? my_out_pts = ~np.isnan(data_comb[0]) * ~np.isnan(data_comb[1]) * \ np.isnan(interp_data) # Don't do this if this is a test with fullgrid_x ... ax1.scatter(data_comb[0][my_out_pts], data_comb[1][my_out_pts], marker = '^', facecolor = 'none', edgecolor = 'k', s=60) # 3) Plot the colorbar cb_ax = plt.subplot(gs[0,1]) cb = Colorbar(ax = cb_ax, mappable = pts, orientation='vertical') # Colorbar legend cb.set_label(color_mode, labelpad = 10) # 4) Axis names, kappa value, etc ... rats = ratios.split(';') # Make sure the labels look pretty in ALL cases ... labelx,labely = get_plot_labels(rats,coeffs) ax1.set_xlabel(labelx,labelpad = 10) ax1.set_ylabel(labely,labelpad = 10) if not(kappa in [np.inf, 'inf']) : kappa_str = r'$\kappa$ = '+str(kappa) else : kappa_str = r'$\kappa$ = $\infty$' ax1.text(0.85,0.9,kappa_str, horizontalalignment='left',verticalalignment='bottom', transform=ax1.transAxes) ax1.grid(True) if figname : fig.savefig(figname, bbox_inches='tight') if show_plot: plt.show() else: plt.close()
def plot_global_qz(pickle_fn, do_all_diags = True, show_plots = True, save_loc = None): ''' A plotting function designed to plot the pickle output from pyqz.get_global_qz(). :Args: pickel_fn: string the path+filename of the pickle filed to process. do_all_diags: bool [default: True] Whether to construct the diagnostic grid plots for all individual diagnostics or not. show_plots: bool [default: True] Whether to display the plots or not. save_loc: string [default: None][ If set, the location where the plots will be saved. If not set, no plots will be saved. :Notes: You must set KDE_pickle_loc to the location of your choice when running pyqz.get_global_qz() and pyqz.get_global_qz_ff(), if you want the associated pickle file to be generated. ''' # 0) Open the pickle file, and check what we are dealing with ... ftmp = open(pickle_fn,'r') KDE_frompickle = pickle.load(ftmp) ftmp.close() # What will I call my plots ? ids = KDE_frompickle['ids'] Pk = KDE_frompickle['Pk'] kappa = KDE_frompickle['kappa'] struct = KDE_frompickle['struct'] sampling = KDE_frompickle['sampling'] KDE_method = KDE_frompickle['KDE_method'] fn_in = pyqz_tools.get_KDE_picklefn(ids, Pk, kappa, struct, sampling, KDE_method) # First things first. Generate the grid plots for all the diagnostics. --------------- discrete_pdf = KDE_frompickle['discrete_pdf'] rsf = KDE_frompickle['rsf'] rsf_keys = KDE_frompickle['rsf_keys'] if do_all_diags: for key in discrete_pdf.keys(): # Reconstruct the line flux mix from the raw rsf data Rval = [] for (r,ratio) in enumerate(key.split('|')[0].split(';')): l1 = ratio.split('/')[0] l2 = ratio.split('/')[1] Rval.append(np.log10(rsf[:,rsf_keys.index(l1)]/ rsf[:,rsf_keys.index(l2)])) if save_loc: plot_name = os.path.join(save_loc, fn_in[:-4] + '_' + key.replace('/','-').replace(';','_vs_').replace('|','_') + '.pdf') else: plot_name = None plot_grid(key.split('|')[0], coeffs = diagnostics[key.split('|')[0]]['coeffs'], Pk = Pk, kappa=kappa, struct = struct, sampling = sampling, color_mode = key.split('|')[1], figname = plot_name, show_plot = show_plots, data = Rval, interp_data = discrete_pdf[key]) # Let's get started with the KDE plot ------------------------------------------------ plt.figure(figsize=(13,8)) gs = gridspec.GridSpec(2,2, height_ratios=[0.05,1.], width_ratios=[1.,1.]) gs.update(left=0.1, right=0.95, bottom=0.1,top=0.9, wspace=0.15, hspace=0.07 ) ax1 = plt.subplot(gs[1,0]) ax2 = plt.subplot(gs[1,1]) # First, the direct estimates -------------------------------------------------------- qzs = KDE_frompickle['qzs'] which_grids = KDE_frompickle['which_grids'] # Create an array to keep track of how big my zoom window will be for ax2 ax2_lims = [np.nan, np.nan, np.nan, np.nan] for (k,key) in enumerate(discrete_pdf.keys()): # Make sure we show each point only once if not(qzs[0] in key): continue # Don't do anything if the point lands outside the plot. if np.isnan(discrete_pdf[key][0]): continue this_diag = key.split('|')[0] for ax in [ax1,ax2]: # The individual realizations ax.scatter(discrete_pdf[this_diag+'|'+qzs[0]][1:], discrete_pdf[this_diag+'|'+qzs[1]][1:], c='k', marker = 'o', s = 1, zorder = 2) # Update the zoom-window limits if required ax2_lims = [np.nanmin(( ax2_lims[0], np.nanmin(discrete_pdf[this_diag+'|'+qzs[0]][1:]) )), np.nanmax(( ax2_lims[1], np.nanmax(discrete_pdf[this_diag+'|'+qzs[0]][1:]) )), np.nanmin(( ax2_lims[2], np.nanmin(discrete_pdf[this_diag+'|'+qzs[1]][1:]) )), np.nanmax(( ax2_lims[3], np.nanmax(discrete_pdf[this_diag+'|'+qzs[1]][1:]) )), ] # The direct estimate ax.plot(discrete_pdf[this_diag+'|'+qzs[0]][0], discrete_pdf[this_diag+'|'+qzs[1]][0], c='w', marker = 's',markeredgewidth=1.5, markerfacecolor='w', markeredgecolor='k', markersize=11, zorder=10) grid_number = which_grids.index(this_diag)+1 ax.text(discrete_pdf[this_diag+'|'+qzs[0]][0], discrete_pdf[this_diag+'|'+qzs[1]][0], grid_number, size=12, ha='center',va='center', zorder=11, color='k') if ax == ax1: # And also add the name of the diagnostic ax.text(QZs_lim[qzs[0]][0] +0.05, QZs_lim[qzs[1]][1] - 0.05*grid_number, '%i: %s' % (grid_number,this_diag), horizontalalignment = 'left', verticalalignment = 'center') # Now, plot the global KDE and the associated contours ------------------------------- all_gridZ = KDE_frompickle['all_gridZ'] gridX = KDE_frompickle['gridX'] gridY = KDE_frompickle['gridY'] final_data = KDE_frompickle['final_data'] final_cols = KDE_frompickle['final_cols'] # Loop through all reconstructed KDEs. Plot all the contours, but only the full KDE. kde = False for gridZ_key in all_gridZ.keys(): # If it is just some nans, go no further if np.all(np.isnan(all_gridZ[gridZ_key])): continue # Careful here: gridZ has a weird arrangement ... gridZ = np.rot90(all_gridZ[gridZ_key])[::-1,:] for ax in [ax1,ax2]: if gridZ_key == 'all': my_c = 'darkorange' my_c2 = 'none' my_lw = 2.5 my_zo = 7 # Plot the KDE kde = ax.imshow(gridZ, extent=[QZs_lim[qzs[0]][0], QZs_lim[qzs[0]][1], QZs_lim[qzs[1]][0], QZs_lim[qzs[1]][1], ], cmap=pyqz_cmap_1, origin='lower', zorder=0, interpolation='nearest') else: my_c = 'royalblue' my_c2 = 'none' my_lw = 1.5 my_zo = 3 # Plot the contour (two times for the look) # Mind the fact that gridX and gridY refer to the "un-derotated" gridZ ! kde_cont = ax.contour(gridX, gridY, all_gridZ[gridZ_key], [PDF_cont_level], colors = my_c, linestyles = '-', linewidths = my_lw, zorder = my_zo) # Plot the individual and global KDE estimates ------------------------------- if gridZ_key == 'all': final_keys = ['<'+qzs[0]+'{KDE}>','err('+qzs[0]+'{KDE})', '<'+qzs[1]+'{KDE}>','err('+qzs[1]+'{KDE})'] else: final_keys = [gridZ_key+'|'+qzs[0]+'{KDE}', 'err('+gridZ_key+'|'+qzs[0]+'{KDE})', gridZ_key+'|'+qzs[1]+'{KDE}', 'err('+gridZ_key+'|'+qzs[1]+'{KDE})'] mean_est = [final_data[final_cols.index(final_keys[0])], final_data[final_cols.index(final_keys[2])]] err_est = [final_data[final_cols.index(final_keys[1])], final_data[final_cols.index(final_keys[3])]] ax.errorbar(mean_est[0], mean_est[1], xerr = err_est[0],yerr = err_est[1], elinewidth = 2., ecolor = my_c, capthick = 0, zorder = my_zo) ax.plot(mean_est[0], mean_est[1], c = my_c, marker = 'o', markersize = 10, markeredgecolor = my_c, markerfacecolor = my_c2, markeredgewidth = 2, zorder = my_zo) # Plot the combined direct estimates ------------------------------------------------- final_keys = ['<'+qzs[0]+'>','std('+qzs[0]+')', '<'+qzs[1]+'>','std('+qzs[1]+')'] mean_est = [final_data[final_cols.index(final_keys[0])], final_data[final_cols.index(final_keys[2])]] err_est = [final_data[final_cols.index(final_keys[1])], final_data[final_cols.index(final_keys[3])]] # Only if that value actually exists ! if not(np.any(np.isnan(mean_est))): for ax in [ax1,ax2]: ax.errorbar(mean_est[0], mean_est[1], xerr = err_est[0], yerr = err_est[1], elinewidth = 2, ecolor = 'k', capthick = 0, zorder = 8) ax.plot(mean_est[0],mean_est[1], '*', c = 'w', markeredgecolor = 'k', markeredgewidth = 2, markerfacecolor = 'w', markersize = 20, zorder = 9) # Very well, finalize the plot now. for ax in [ax1, ax2]: ax.set_xlabel(qzs[0]) ax.grid(True) # Set the left plot to cover the full extent of the qz plane ax1.set_xlim(QZs_lim[qzs[0]]) ax1.set_ylim(QZs_lim[qzs[1]]) ax1.set_ylabel(qzs[1]) # Define the limits for the right plot - a zoomed-in version if np.any(np.isnan(ax2_lims)): ax2.set_xlim(QZs_lim[qzs[0]]) ax2.set_ylim(QZs_lim[qzs[1]]) else: ax2.set_xlim(ax2_lims[:2]) ax2.set_ylim(ax2_lims[2:]) # Plot the window of the right plot in the left one rectx = [ax2_lims[0], ax2_lims[1], ax2_lims[1], ax2_lims[0], ax2_lims[0]] recty = [ax2_lims[2], ax2_lims[2], ax2_lims[3], ax2_lims[3], ax2_lims[2]] ax1.plot(rectx,recty, 'k--', lw = 1.5, markersize=5,zorder=1) ax2.set_aspect('auto') ax1.set_aspect('auto') ax1.locator_params(axis='x',nbins=5) ax2.locator_params(axis='x',nbins=5) # Plot the colorbar if required if kde: cb_ax = plt.subplot(gs[0,:]) cb = Colorbar(ax = cb_ax, mappable = kde, orientation='horizontal') # Colorbar legend cb.set_label(r'Joint Probability Density (normalized to peak)', labelpad = -60) cb.ax.xaxis.set_ticks_position('top') cb.solids.set_edgecolor('face') # Draw the 1-sigma level (assuming gaussian = 61% of the peak) cb.ax.axvline(x = PDF_cont_level, color = 'darkorange', linewidth = 3, linestyle = '-') # Get ready to save this: if save_loc: plot_name = os.path.join(save_loc, fn_in[:-3]+'pdf') plt.savefig(plot_name, bbox_inches='tight') if show_plots: plt.show() else: plt.close() # ----------------------------------------------------------------------------------------
def save_3Dimages(data, names, z_index, path_name, image_name): plt.figure(figsize=(len(data) * 8, 12)) logging.info("plot len data", len(data)) grid = plt.GridSpec(5, len(data), height_ratios=[0.01, 0.3, 0.1, 0.02, 0.01], width_ratios=len(data) * [1]) logging.info("shape data save", np.shape(data)) for img, image in enumerate(data): shape = np.shape(image) logging.info("shape image", np.shape(image)) x_image = image[int(shape[0] / 2), ...] z_image = image[:, int(shape[1] / 2), :] logging.info("shape plot image", np.shape(x_image)) plts = plt.subplot(grid[0:2, img]) plts = plt.plot(np.arange(np.shape(x_image)[1]), [np.shape(x_image)[1] / 2] * np.shape(x_image)[1], color='0.5') plts = plt.title(names[img], size=50) plts = plt.tick_params(labelsize=50) plts = plt.xticks([]) if img > 0: plts = plt.yticks([]) if img == 0: plts = plt.ylabel("y (Pixel)", size=50) plts = plt.yticks(size=40) if names[img] == "abs_errormap": max_val = np.max(np.abs(x_image)) pltcberror = plt.imshow(rgb2gray(x_image), cmap='seismic', vmin=-max_val, vmax=max_val) pltcberror = plt.subplot(grid[2, img]) pltcberror = plt.plot(np.arange(np.shape(z_image)[1]), [np.shape(z_image)[0] / 2] * np.shape(z_image)[1], color='0.5') elif names[img] == "uncertainty": max_val = np.max(np.abs(x_image)) pltcbunc = plt.title("uncertainty", size=50) pltcunc = plt.imshow(rgb2gray(x_image), cmap='Greys', vmin=-max_val, vmax=max_val) pltcunc = plt.subplot(grid[2, img]) pltcunc = plt.plot(np.arange(np.shape(z_image)[1]), [np.shape(z_image)[0] / 2] * np.shape(z_image)[1], color='0.5') else: pltxz = plt.imshow(x_image, cmap='Greys') pltxz = plt.subplot(grid[2, img]) pltxz = plt.plot(np.arange(np.shape(z_image)[1]), [np.shape(z_image)[0] / 2] * np.shape(z_image)[1], color='0.5') if img > 0: pltxy = plt.tick_params(axis='y', labelleft=False) pltxy = plt.tick_params(labelsize=40) pltxz = plt.yticks([]) if img == 0: pltxz = plt.ylabel("y (Pixel)", size=50) if names[img] == "abs_errormap": max_val = np.max(np.abs(x_image)) pltcerror = plt.imshow(rgb2gray(z_image), cmap='seismic', vmin=-max_val, vmax=max_val) pltcberror = plt.yticks([]) elif names[img] == "uncertainty": max_val = np.max(np.abs(x_image)) pltcunc = plt.imshow(rgb2gray(np.max(z_image) - z_image), cmap='Greys', vmin=-max_val, vmax=max_val) else: pltz = plt.imshow(z_image, cmap='Greys') pltz = plt.tick_params(labelsize=40) pltz = plt.xlabel("x (Pixel)", size=50) if img == 0: pltz = plt.ylabel("z (Pixel)", size=50) if img > 0: pltz = plt.tick_params(axis='y', labelleft=False, labelsize=40) # pltz = plt.tick_params(labelsize=40) if "abs_errormap" in names: if "uncertainty" in names: cbax = plt.subplot(grid[3:4, -2]) else: cbax = plt.subplot(grid[3:4, -1]) cbax = Colorbar(ax=cbax, mappable=pltcerror, orientation="horizontal") cbax.set_ticks([]) cbax.set_label('Over- Under- \n prediction', size=50) cbax.ax.tick_params(labelsize=50) if "uncertainty" in names: cbax = plt.subplot(grid[3:4, -1]) cbax = Colorbar(ax=cbax, mappable=pltcunc, orientation="horizontal") cbax.set_ticks([]) cbax.set_label('Low High', size=50) cbax.ax.tick_params(labelsize=50) logging.info(path_name + z_index + image_name + ".png") plt.savefig(path_name + z_index + image_name + ".png", dpi=50, bbox_inches='tight') plt.show() plt.close()
def render_figure(halo_number, redshift, projection, output="Show"): plotpar.set_defaults_plot() nullfmt = NullFormatter() fig = plt.figure(1, figsize=(10, 13)) # Now, create the gridspec structure, as required gs = gridspec.GridSpec(ncols=3, nrows=7, height_ratios=[0.05, 1, 0.5, 0.7, 0.05, 1, 0.5], width_ratios=[1, 1, 0.5]) # 3 rows, 4 columns, each with the required size ratios. # Also make sure the margins and spacing are apropriate gs.update(left=0.05, right=0.95, bottom=0.08, top=0.93, wspace=0.08, hspace=0.08) # Note: I set the margins to make it look good on my screen ... # BUT: this is irrelevant for the saved image, if using bbox_inches='tight'in savefig ! # Note: Here, I use a little trick. I only have three vertical layers of plots : # a scatter plot, a histogram, and a line plot. So, in principle, I could use a 3x3 structure. # However, I want to have the histogram 'closer' from the scatter plot than the line plot. # So, I insert a 4th layer between the histogram and line plot, # keep it empty, and use its thickness (the 0.2 above) to adjust the space as required. selection_color = 'coral' # selection_color = 'lime' colormap = 'YlGnBu_r' alpha_select = 0.1 # LABELS label_n = r'$n_{sub}$' label_M = r'$M/M_\odot$' label_R = r'$R/R_{200}$' label_f = r'$f_{g}$' label_v = r'$v_{z}/\mathrm{(km\ s^{-1})}$' # GRIDS & NBINS grid_on = False # loop over plots for j in [0, 4]: for i in [0, 1]: print('Block started') if i == 0 and j == 0: x = data_dict['R'] y = data_dict['Fg'] SELECT_x_min, SELECT_x_max = selec_dict[ 'SELECT_R_MIN'], selec_dict['SELECT_R_MAX'] SELECT_y_min, SELECT_y_max = selec_dict[ 'SELECT_Fg_MIN'], selec_dict['SELECT_Fg_MAX'] if i == 1 and j == 0: x = data_dict['M'] y = data_dict['Fg'] SELECT_x_min, SELECT_x_max = selec_dict[ 'SELECT_M_MIN'], selec_dict['SELECT_M_MAX'] SELECT_y_min, SELECT_y_max = selec_dict[ 'SELECT_Fg_MIN'], selec_dict['SELECT_Fg_MAX'] if i == 0 and j == 4: x = data_dict['R'] y = data_dict['Vr'] SELECT_x_min, SELECT_x_max = selec_dict[ 'SELECT_R_MIN'], selec_dict['SELECT_R_MAX'] SELECT_y_min, SELECT_y_max = selec_dict[ 'SELECT_Vr_MIN'], selec_dict['SELECT_Vr_MAX'] if i == 1 and j == 4: x = data_dict['M'] y = data_dict['Vr'] SELECT_x_min, SELECT_x_max = selec_dict[ 'SELECT_M_MIN'], selec_dict['SELECT_M_MAX'] SELECT_y_min, SELECT_y_max = selec_dict[ 'SELECT_Vr_MIN'], selec_dict['SELECT_Vr_MAX'] x_min_LIN, x_max_LIN = np.min(x), np.max(x) x_min_LOG, x_max_LOG = np.log10(x_min_LIN), np.log10(x_max_LIN) y_min_LIN, y_max_LIN = np.min(y), np.max(y) if j == 0: y_min_LIN, y_max_LIN = 0, 0.3 # First, the scatter plot ax1 = fig.add_subplot(gs[j + 1, i]) print('\tComputing 2dhist \t\t (%1i, %1i)' % (j + 1, i)) # # Get the optimal number of bins based on knuth_bin_width # N_xbins = int((np.max(x)-np.min(x))/knuth_bin_width(x)) + 1 # N_ybins = int((np.max(y)-np.min(y))/knuth_bin_width(y)) + 1 N_xbins = 50 N_ybins = N_xbins bins_LOG = np.logspace(x_min_LOG, x_max_LOG, num=N_xbins) bins_LIN = np.linspace(y_min_LIN, y_max_LIN, num=N_ybins) Cx, Cy = mapgen.bins_meshify(x, y, bins_LOG, bins_LIN) count = mapgen.bins_evaluate(x, y, bins_LOG, bins_LIN, weights=None) norm = colors.LogNorm() plt1 = ax1.pcolor(Cx, Cy, count, cmap=colormap, norm=norm) ax1.grid(grid_on) ax1.set_xlim([x_min_LIN, x_max_LIN]) ax1.set_ylim([y_min_LIN, y_max_LIN]) ax1.set_xscale('log') ax1.set_yscale('linear') ax1.set_xlabel(r' ') # Force this empty ! ax1.xaxis.set_major_formatter(nullfmt) ax1.set_ylabel(label_f) if j == 4: ax1.axhspan(-SELECT_y_max, -SELECT_y_min, alpha=alpha_select, color=selection_color) rect2 = patches.Rectangle((SELECT_x_min, -SELECT_y_max), SELECT_x_max - SELECT_x_min, -SELECT_y_min + SELECT_y_max, linewidth=1.5, edgecolor='r', facecolor='none') ax1.add_patch(rect2) ax1.axvspan(SELECT_x_min, SELECT_x_max, alpha=alpha_select, color=selection_color) ax1.axhspan(SELECT_y_min, SELECT_y_max, alpha=alpha_select, color=selection_color) rect = patches.Rectangle((SELECT_x_min, SELECT_y_min), SELECT_x_max - SELECT_x_min, SELECT_y_max - SELECT_y_min, linewidth=1.5, edgecolor='r', facecolor='none') ax1.add_patch(rect) if j == 0: ax1.set_ylabel(label_f) elif j == 4: ax1.set_ylabel(label_v) # Colorbar cbax = fig.add_subplot(gs[j, i]) print('\tComputing colorbar \t\t (%1i, %1i)' % (j, i)) cb = Colorbar(ax=cbax, mappable=plt1, orientation='horizontal', ticklocation='top') cb.set_label(label_n, labelpad=10) trig_vertical_hist = 0 # VERTICAL HISTOGRAM if i != 0: ax1v = fig.add_subplot(gs[j + 1, i + 1]) print('\tComputing vert hist \t (%1i, %1i)' % (j + 1, i + 1)) ax1v.hist(y, bins=bins_LIN, orientation='horizontal', color='k', histtype='step') ax1v.hist(y, bins=bins_LIN, orientation='horizontal', color='red', histtype='step', cumulative=-1) ax1v.set_yticks(ax1.get_yticks( )) # Ensures we have the same ticks as the scatter plot ! ax1v.set_xlabel(label_n) ax1v.tick_params(labelleft=False) ax1v.set_ylim(ax1.get_ylim()) ax1v.set_xscale('log') ax1v.set_yscale('linear') ax1v.grid(grid_on) ax1v.axhspan(SELECT_y_min, SELECT_y_max, alpha=alpha_select, color=selection_color) if j == 4: ax1v.axhspan(-SELECT_y_max, -SELECT_y_min, alpha=alpha_select, color=selection_color) ax1.yaxis.set_major_formatter(nullfmt) ax1.set_ylabel('') trig_vertical_hist = 1 # Percentiles percents = [15.9, 50, 84.1] percent_str = [r'$16\%$', r'$50\%$', r'$84\%$'] clr = ['orange', 'blue', 'green'] percent_ticks = np.percentile(y, percents) if trig_vertical_hist: percent_str = np.flipud(percent_str) clr = np.flipud(clr) ax1v_TWIN = ax1v.twinx() ax1v_TWIN.set_ylim(ax1.get_ylim()) ax1v_TWIN.tick_params(axis='y', which='both', labelleft='off', labelright='on') ax1v_TWIN.set_yticks(percent_ticks) ax1v_TWIN.set_yticklabels(percent_str) for percent_tick, c, tick in zip( percent_ticks, clr, ax1v_TWIN.yaxis.get_major_ticks()): tick.label1.set_color(c) ax1v_TWIN.axhline(y=percent_tick, color=c, linestyle='--') percent_str = np.flipud(percent_str) clr = np.flipud(clr) # HORIZONTAL HISTOGRAM ax1h = fig.add_subplot(gs[j + 2, i]) print('\tComputing horiz hist \t (%1i, %1i)' % (j + 2, i)) ax1h.hist(x, bins=bins_LOG, orientation='vertical', color='k', histtype='step') ax1h.hist(x, bins=bins_LOG, orientation='vertical', color='red', histtype='step', cumulative=True) ax1h.set_xticks(ax1.get_xticks( )) # Ensures we have the same ticks as the scatter plot ! ax1h.set_xlim(ax1.get_xlim()) if i == 0: ax1h.set_xlabel(label_R) ax1h.set_ylabel(label_n) elif i == 1: ax1h.set_xlabel(label_M) ax1h.tick_params(labelleft=False) ax1h.set_ylabel('') ax1h.set_xscale('log') ax1h.set_yscale('log') ax1h.grid(grid_on) ax1h.axvspan(SELECT_x_min, SELECT_x_max, alpha=alpha_select, color=selection_color) percent_ticks = np.percentile(x, percents) for i in range(len(percents)): ax1h.axvline(x=percent_ticks[i], color=clr[i], linestyle='--') print('Block completed\n') if output.lower() == 'show': fig.show() elif output.lower() == 'save': dir_name = 'Subfind-Selection' if not exists(dir_name): makedirs(dir_name) save_name = 'selection-phase-space_halo' + str( halo_number) + '_z' + str(redshift).replace( ".", "") + '_proj' + str(projection) + '.pdf' fig.savefig(dir_name + '//' + save_name, dpi=None, facecolor='w', edgecolor='w', orientation='portrait', papertype=None, format=None, transparent=False, bbox_inches='tight', pad_inches=0.1, frameon=None) elif output.lower() == 'none': pass else: print("Error: Invalid request")
def save_2Dimages(data, names, z_index, path_name, image_name): logging.info("plot len data") logging.info(len(data)) plt.figure(figsize=(len(data) * 8, 10)) grid = plt.GridSpec(4, len(data), height_ratios=[0.01, 0.3, 0.02, 0.01], width_ratios=len(data) * [1]) logging.info("shape data save") logging.info(np.shape(data)) for img, image in enumerate(data): shape = np.shape(image) #logging.info("shape plot image", np.shape(image)) plts = plt.subplot(grid[0:2, img]) if names[img] == "abs_errormap": max_val = np.max(np.abs(image)) pltcberror = plt.title("errormap", size=50) pltcberror = plt.imshow(rgb2gray(image), cmap='seismic', vmin=-max_val, vmax=max_val) elif names[img] == "uncertainty": plts = plt.title(names[img] + str(np.mean(image)), size=50) max_val = np.max(np.abs(image)) pltcbunc = plt.title("uncertainty", size=50) pltcbunc = plt.imshow(np.max(image) - rgb2gray(image), cmap='Greys', vmin=-max_val, vmax=max_val) else: plts = plt.imshow(rgb2gray(image), cmap='Greys') plts = plt.title(names[img], size=50) pltz = plt.xlabel("x (Pixel)", size=50) if img == 0: pltz = plt.ylabel("y (Pixel)", size=50) plts = plt.tick_params(labelsize=50) if img > 0: plts = plt.tick_params(axis='y', labelleft=False) plts = plt.tick_params(labelsize=50) if names[img] == "abs_errormap": logging.info("colorbar") if "uncertainty" in names: cbax = plt.subplot(grid[2:3, -2]) else: cbax = plt.subplot(grid[2:3, -1]) cbax = Colorbar(ax=cbax, mappable=pltcberror, orientation="horizontal") cbax.set_ticks([]) cbax.set_label('Over- Under- \n prediction', size=50) if names[img] == "uncertainty": logging.info("colorbar uncertanty") cbay = plt.subplot(grid[2:3, -1]) cbay = Colorbar(ax=cbay, mappable=pltcbunc, orientation="horizontal") cbay.set_ticks([]) cbay.set_label('Low High', size=50) plt.savefig(os.path.join(path_name, z_index + image_name + ".png"), dpi=50, bbox_inches='tight') plt.show() plt.close()
def vetting_field_of_view(self, indir, tic, ra, dec, sectors): maglim = 6 sectors_search = None if sectors is not None and len( sectors) == 0 else sectors tpf_source = lightkurve.search_targetpixelfile("TIC " + str(tic), sector=sectors, mission='TESS') if tpf_source is None or len(tpf_source) == 0: ra_str = str(ra) dec_str = "+" + str(dec) if dec >= 0 else str(dec) tpf_source = lightkurve.search_tesscut(ra_str + " " + dec_str, sector=sectors_search) for i in range(0, len(tpf_source)): tpf = tpf_source[i].download(cutout_size=(12, 12)) pipeline = True fig = plt.figure(figsize=(6.93, 5.5)) gs = gridspec.GridSpec(1, 3, height_ratios=[1], width_ratios=[1, 0.05, 0.01]) gs.update(left=0.05, right=0.95, bottom=0.12, top=0.95, wspace=0.01, hspace=0.03) ax1 = plt.subplot(gs[0, 0]) # TPF plot mean_tpf = np.mean(tpf.flux.value, axis=0) nx, ny = np.shape(mean_tpf) norm = ImageNormalize(stretch=stretching.LogStretch()) division = np.int(np.log10(np.nanmax(tpf.flux.value))) splot = plt.imshow(np.nanmean(tpf.flux, axis=0) / 10 ** division, norm=norm, \ extent=[tpf.column, tpf.column + ny, tpf.row, tpf.row + nx], origin='lower', zorder=0) # Pipeline aperture if pipeline: # aperture_mask = tpf.pipeline_mask aperture = tpf._parse_aperture_mask(aperture_mask) maskcolor = 'lightgray' print(" --> Using pipeline aperture...") else: aperture_mask = tpf.create_threshold_mask( threshold=10, reference_pixel='center') aperture = tpf._parse_aperture_mask(aperture_mask) maskcolor = 'lightgray' print(" --> Using threshold aperture...") for i in range(aperture.shape[0]): for j in range(aperture.shape[1]): if aperture_mask[i, j]: ax1.add_patch( patches.Rectangle((j + tpf.column, i + tpf.row), 1, 1, color=maskcolor, fill=True, alpha=0.4)) ax1.add_patch( patches.Rectangle((j + tpf.column, i + tpf.row), 1, 1, color=maskcolor, fill=False, alpha=1, lw=2)) # Gaia sources gaia_id, mag = tpfplotter.get_gaia_data_from_tic(tic) r, res = tpfplotter.add_gaia_figure_elements(tpf, magnitude_limit=mag + np.float(maglim), targ_mag=mag) x, y, gaiamags = r x, y, gaiamags = np.array(x) + 0.5, np.array(y) + 0.5, np.array( gaiamags) size = 128.0 / 2**((gaiamags - mag)) plt.scatter(x, y, s=size, c='red', alpha=0.6, edgecolor=None, zorder=10) # Gaia source for the target this = np.where(np.array(res['Source']) == int(gaia_id))[0] plt.scatter(x[this], y[this], marker='x', c='white', s=32, zorder=11) # Legend add = 0 if np.int(maglim) % 2 != 0: add = 1 maxmag = np.int(maglim) + add legend_mags = np.linspace(-2, maxmag, np.int((maxmag + 2) / 2 + 1)) fake_sizes = mag + legend_mags # np.array([mag-2,mag,mag+2,mag+5, mag+8]) for f in fake_sizes: size = 128.0 / 2**((f - mag)) plt.scatter(0, 0, s=size, c='red', alpha=0.6, edgecolor=None, zorder=10, label=r'$\Delta m=$ ' + str(np.int(f - mag))) ax1.legend(fancybox=True, framealpha=0.7) # Source labels dist = np.sqrt((x - x[this])**2 + (y - y[this])**2) dsort = np.argsort(dist) for d, elem in enumerate(dsort): if dist[elem] < 6: plt.text(x[elem] + 0.1, y[elem] + 0.1, str(d + 1), color='white', zorder=100) # Orientation arrows tpfplotter.plot_orientation(tpf) # Labels and titles plt.xlim(tpf.column, tpf.column + ny) plt.ylim(tpf.row, tpf.row + nx) plt.xlabel('Pixel Column Number', fontsize=16) plt.ylabel('Pixel Row Number', fontsize=16) plt.title('Coordinates ' + tic + ' - Sector ' + str(tpf.sector), fontsize=16) # + ' - Camera '+str(tpf.camera)) # # Colorbar cbax = plt.subplot(gs[0, 1]) # Place it where it should be. pos1 = cbax.get_position() # get the original position pos2 = [pos1.x0 - 0.05, pos1.y0, pos1.width, pos1.height] cbax.set_position(pos2) # set a new position cb = Colorbar(ax=cbax, mappable=splot, orientation='vertical', ticklocation='right') plt.xticks(fontsize=14) exponent = r'$\times 10^' + str(division) + '$' cb.set_label(r'Flux ' + exponent + r' (e$^-$)', labelpad=10, fontsize=16) save_dir = indir + "/tpfplot" if not os.path.exists(save_dir): os.makedirs(save_dir) plt.savefig(save_dir + '/TPF_Gaia_TIC' + tic + '_S' + str(tpf.sector) + '.pdf') # Save Gaia sources info dist = np.sqrt((x - x[this])**2 + (y - y[this])**2) GaiaID = np.array(res['Source']) srt = np.argsort(dist) x, y, gaiamags, dist, GaiaID = x[srt], y[srt], gaiamags[srt], dist[ srt], GaiaID[srt] IDs = np.arange(len(x)) + 1 inside = np.zeros(len(x)) for i in range(aperture.shape[0]): for j in range(aperture.shape[1]): if aperture_mask[i, j]: xtpf, ytpf = j + tpf.column, i + tpf.row _inside = np.where((x > xtpf) & (x < xtpf + 1) & (y > ytpf) & (y < ytpf + 1))[0] inside[_inside] = 1 data = Table([ IDs, GaiaID, x, y, dist, dist * 21., gaiamags, inside.astype('int') ], names=[ '# ID', 'GaiaID', 'x', 'y', 'Dist_pix', 'Dist_arcsec', 'Gmag', 'InAper' ]) ascii.write(data, save_dir + '/Gaia_TIC' + tic + '_S' + str(tpf.sector) + '.dat', overwrite=True) return save_dir
def _plot_eff_array(array_dict, use_contour = True, out_name = 'rejrej.pdf'): eff_array = array_dict['eff'] eff_array = _maximize_efficiency(eff_array) x_min, x_max = array_dict['x_range'] y_min, y_max = array_dict['y_range'] eff_array[np.nonzero(eff_array < 0.0)] = np.nan fig = plt.figure() gs = GridSpec(20,21) ax = plt.subplot(gs[:,0:-1]) aspect = float(x_max - x_min) / (y_max - y_min) im = ax.imshow( eff_array, origin = 'upper', extent = (x_min,x_max, y_min, y_max), aspect = aspect, interpolation = 'nearest', vmin = 0, vmax = 1, ) if use_contour: im.set_cmap('Greys') ct = ax.contour( eff_array, origin = 'upper', extent = (x_min,x_max, y_min, y_max), aspect = aspect, linewidths = 2, levels = np.arange(0.1,1.0,0.1), ) im.get_cmap().set_bad(alpha=0) ax.set_xticks([]) ax.set_yticks([]) ax.invert_yaxis() cb_ax = plt.subplot(gs[:,-1]) plt.subplots_adjust(left = 0.25) # FIXME: use OO call here # cb = plt.colorbar() cb = Colorbar(ax = cb_ax, mappable = im) cb.set_label('{} efficiency'.format(array_dict['signal'])) if use_contour: cb.add_lines(ct) position = ax.get_position() new_aspect = ax.get_aspect() # ax.set_position(position) ax_log = fig.add_subplot(111, frameon = False) ax_log.set_xscale('log') ax_log.set_yscale('log') ax_log.axis((10**x_min, 10**x_max, 10**y_min, 10**y_max)) ax_log.set_aspect(aspect) ax_log.set_xlabel('{} rejection'.format(array_dict['x_bg'])) ax_log.set_ylabel('{} rejection'.format(array_dict['y_bg'])) ax_log.grid(True) ax_log.set_aspect(new_aspect) ax_log.set_position(position) plt.savefig(out_name, bbox_inches = 'tight') plt.close()
else: # plt.title('TIC ' + tic + ' - Sector ' + str(tpf.sector), fontsize=16) # + ' - Camera '+str(tpf.camera)) # Colorbar cbax = plt.subplot(gs[0, 1]) # Place it where it should be. pos1 = cbax.get_position() # get the original position pos2 = [pos1.x0 - 0.05, pos1.y0, pos1.width, pos1.height] cbax.set_position(pos2) # set a new position cb = Colorbar(ax=cbax, mappable=splot, orientation='vertical', ticklocation='right') plt.xticks(fontsize=14) cb.set_label(r'Flux $\times 10^4$ (e$^-$)', labelpad=10, fontsize=16) plt.savefig('TPF_Gaia_TIC' + tic + '.pdf') # Save Gaia sources info if args.SAVEGAIA: dist = np.sqrt((x - x[this])**2 + (y - y[this])**2) GaiaID = np.array(res['Source']) srt = np.argsort(dist) x, y, gaiamags, dist, GaiaID = x[srt], y[srt], gaiamags[srt], dist[ srt], GaiaID[srt] IDs = np.arange(len(x)) + 1 inside = np.zeros(len(x)) for i in range(aperture.shape[0]):
def plot_grid(ratios, coeffs=[[1, 0], [0, 1]], Pk=5.0, kappa=np.inf, struct='pp', sampling=1, color_mode='Tot[O]+12', figname=None, show_plot=True, data=None, interp_data=None): ''' Creates the diagram of a given line ratio grid for rapid inspection, including wraps (fold-over regions), and of certain line ratios, if "data" is specified. :Args: ratios: string The line ratios defining the grid, e.g. '[NII]/[SII]+;[OIII]/Hb' coeffs: list of list [default: [[1,0],[0,1]] ] The different coefficients with which to mix the line ratios. The size of each sub-list must be equal to the number of line ratios involved. Used for projected 3D diagnostic grids. Pk: float [default: 5.0] MAPPINGS model pressure. This value must match an existing grid file. kappa: float [default: np.inf The kappa value. This value must match an existing grid file. struct: string [default: 'pp'] spherical ('sph') or plane-parallel ('pp') HII regions. This value must match an existing reference grid file. sampling: int [default: 1] Use a resampled grid ? color_mode: string [default: 'Tot[O]+12'] Color the grid according to 'Tot[O]+12', 'gas[O]+12' or 'LogQ'. figname: string [default: None] 'path+name+format' to save the Figure to. show_plot: bool [default: True] Do you want to display the Figure ? data: list of numpy array [default: None] List of Arrays of the line ratio values. One array per line ratio. interp_data: numpy array [default: 'linear'] interpolated line ratios (via pyqz.interp_qz) ''' # 0) Let's get the data in question [grid, grid_cols, metadata] = pyqz.get_grid(ratios, coeffs=coeffs, Pk=Pk, kappa=kappa, struct=struct, sampling=sampling) # 1) What are the bad segments in this grid ? bad_segs = pyqz.check_grid(ratios, coeffs=coeffs, Pk=Pk, kappa=kappa, struct=struct, sampling=sampling) # 2) Start the plotting fig = plt.figure(figsize=(10, 8)) gs = gridspec.GridSpec(1, 2, height_ratios=[1], width_ratios=[1, 0.05]) gs.update(left=0.14, right=0.88, bottom=0.14, top=0.92, wspace=0.1, hspace=0.1) ax1 = fig.add_subplot(gs[0, 0]) if not (color_mode in grid_cols): raise Exception('color_mode unknown: %s' % color_mode) # 2) Plot the grid points # Let's make the distinction between the 'TRUE' MAPPINGS point, # and those that were interpolated in a finer grid using Akima splines pts = ax1.scatter(grid[:, grid_cols.index('Mix_x')], grid[:, grid_cols.index('Mix_y')], marker='o', c=grid[:, grid_cols.index(color_mode)], s=30, cmap=pyqzm.pyqz_cmap_0, edgecolor='none', vmin=np.min(grid[:, grid_cols.index(color_mode)]), vmax=np.max(grid[:, grid_cols.index(color_mode)]), zorder=3) # Now mark the "original" points with a black outline. First, which are they ? if sampling > 1: origin_cond = [ n for n in range(len(grid)) if (grid[n, metadata['columns'].index('LogQ')] in metadata['resampled']['LogQ']) and ( grid[n, metadata['columns'].index('Tot[O]+12')] in metadata['resampled']['Tot[O]+12']) ] else: origin_cond = [n for n in range(len(grid))] # Now plot the black outlines. original_pts = ax1.scatter(grid[origin_cond, grid_cols.index('Mix_x')], grid[origin_cond, grid_cols.index('Mix_y')], marker='o', c=grid[origin_cond, grid_cols.index(color_mode)], s=60, cmap=pyqzm.pyqz_cmap_0, edgecolor='k', facecolor='white', vmin=np.min(grid[:, grid_cols.index(color_mode)]), vmax=np.max(grid[:, grid_cols.index(color_mode)]), zorder=5) # 2-1) Draw the grid lines # Check as a function of LogQ and Tot[O]+12. Where are these ? u = grid_cols.index('LogQ') v = grid_cols.index('Tot[O]+12') for i in [u, v]: # Here, 'var' plays the role of 'q' or 'z' depending on 'i'. for var in np.unique(grid[:, i]): # Plot the grid line ax1.plot(grid[grid[:, i] == var][:, grid_cols.index('Mix_x')], grid[grid[:, i] == var][:, grid_cols.index('Mix_y')], 'k-', lw=1, zorder=1) # Plot the bad segments for bad_seg in bad_segs: ax1.plot([bad_seg[0][0], bad_seg[1][0]], [bad_seg[0][1], bad_seg[1][1]], 'r-', linewidth=4, zorder=0) # Now, also plot the data, if anything was provided ! if not (interp_data is None): # Compute the combined "observed" ratios data_comb = [np.zeros_like(data[0]), np.zeros_like(data[1])] for k in range(len(ratios.split(';'))): data_comb[0] += coeffs[0][k] * data[k] data_comb[1] += coeffs[1][k] * data[k] ax1.scatter(data_comb[0][interp_data == interp_data], data_comb[1][interp_data == interp_data], marker='s', c=interp_data[interp_data == interp_data], s=15, cmap=pyqzm.pyqz_cmap_0, edgecolor='k', vmin=np.min(grid[:, grid_cols.index(color_mode)]), vmax=np.max(grid[:, grid_cols.index(color_mode)]), zorder=2, alpha=0.35) # Plot also the points outside the grid ? # Which are they ? Need to check if they have a valid input first ! # mind the "~" to invert the bools ! isn't this cool ? my_out_pts = ~np.isnan(data_comb[0]) * ~np.isnan(data_comb[1]) * \ np.isnan(interp_data) # Don't do this if this is a test with fullgrid_x ... ax1.scatter(data_comb[0][my_out_pts], data_comb[1][my_out_pts], marker='^', facecolor='none', edgecolor='k', s=60) # 3) Plot the colorbar cb_ax = plt.subplot(gs[0, 1]) cb = Colorbar(ax=cb_ax, mappable=pts, orientation='vertical') # Colorbar legend cb.set_label(color_mode, labelpad=10) # 4) Axis names, kappa value, etc ... rats = ratios.split(';') # Make sure the labels look pretty in ALL cases ... labelx, labely = get_plot_labels(rats, coeffs) ax1.set_xlabel(labelx, labelpad=10) ax1.set_ylabel(labely, labelpad=10) if not (kappa in [np.inf, 'inf']): kappa_str = r'$\kappa$ = ' + str(kappa) else: kappa_str = r'$\kappa$ = $\infty$' ax1.text(0.85, 0.9, kappa_str, horizontalalignment='left', verticalalignment='bottom', transform=ax1.transAxes) ax1.grid(True) if figname: fig.savefig(figname, bbox_inches='tight') if show_plot: plt.show() else: plt.close()
def diffraction_plot(diffraction, k_values, ax=None, cmap="afmhot", vmin=4e-6, vmax=0.7): """Helper function to plot diffraction pattern. Args: diffraction (:class:`numpy.ndarray`): Diffraction image data. k_values (:class:`numpy.ndarray`): :math:`k` value magnitudes for each bin of the diffraction image. ax (:class:`matplotlib.axes.Axes`): Axes object to plot. If :code:`None`, make a new axes and figure object (Default value = :code:`None`). cmap (str): Colormap name to use (Default value = :code:`'afmhot'`). vmin (float): Minimum of the color scale (Default value = 4e-6). vmax (float): Maximum of the color scale (Default value = 0.7). Returns: :class:`matplotlib.axes.Axes`: Axes object with the diagram. """ import matplotlib.colors from matplotlib.colorbar import Colorbar from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable if ax is None: fig = plt.figure() ax = fig.subplots() # Plot the diffraction image and color bar norm = matplotlib.colors.LogNorm(vmin=vmin, vmax=vmax) extent = (np.min(k_values), np.max(k_values), np.min(k_values), np.max(k_values)) im = ax.imshow( np.clip(diffraction, vmin, vmax), interpolation="nearest", cmap=cmap, norm=norm, extent=extent, ) ax_divider = make_axes_locatable(ax) cax = ax_divider.append_axes("right", size="7%", pad="10%") cb = Colorbar(cax, im) cb.set_label(r"$S(\vec{k})$") # Set tick locations and labels ax.xaxis.set_major_locator( MaxNLocator(nbins=6, symmetric=True, min_n_ticks=7)) ax.yaxis.set_major_locator( MaxNLocator(nbins=6, symmetric=True, min_n_ticks=7)) formatter = FormatStrFormatter("%.3g") ax.xaxis.set_major_formatter(formatter) ax.yaxis.set_major_formatter(formatter) # Set title, limits, aspect ax.set_title("Diffraction Pattern") ax.set_aspect("equal", "datalim") ax.set_xlabel("$k_x$") ax.set_ylabel("$k_y$") return ax
ax0 = pp.subplot(gs[0, 0:10]) ax1 = pp.subplot(gs[0, 12:22]) cb_ax = pp.subplot(gs[0,-1]) ax0.set_title('Base System Transition Matrix') im = ax0.imshow(base_transition_matrix, interpolation='nearest', origin='lower', vmin=0, vmax=1, cmap='gist_earth') ax0.set_xlabel('State [index]') ax0.set_ylabel('State [index]') ax1.set_title('Mutant Transition Matrix') im = ax1.imshow(sampling['transition_matrix'], interpolation='nearest', origin='lower', vmin=0, vmax=1, cmap='gist_earth') ax1.set_xlabel('State [index]') ax1.set_ylabel('State [index]') cb = Colorbar(ax = cb_ax, mappable = im) # use the raw colorbar constructor cb.set_label('Transition Probability') cb.set_ticks([0, 0.25, 0.5, 0.75, 1.0]) #cb = Colorbar(ax=pp.subplot(gs[1, -1]), mappable=lower) #cb.set_ticks(np.asarray(np.unique(trajectory), dtype=int)) #cb.set_label('state') sampling.close() print 'saving figure as %s' % plot_fn pp.savefig(plot_fn) if sys.platform == 'darwin': os.system('open %s' % plot_fn)
def plot_global_qz(pickle_fn, do_all_diags=True, show_plots=True, save_loc=None): ''' A plotting function designed to plot the pickle output from pyqz.get_global_qz(). :Args: pickel_fn: string the path+filename of the pickle filed to process. do_all_diags: bool [default: True] Whether to construct the diagnostic grid plots for all individual diagnostics or not. show_plots: bool [default: True] Whether to display the plots or not. save_loc: string [default: None][ If set, the location where the plots will be saved. If not set, no plots will be saved. :Notes: You must set KDE_pickle_loc to the location of your choice when running pyqz.get_global_qz() and pyqz.get_global_qz_ff(), if you want the associated pickle file to be generated. ''' # 0) Open the pickle file, and check what we are dealing with ... ftmp = open(pickle_fn, 'r') KDE_frompickle = pickle.load(ftmp) ftmp.close() # What will I call my plots ? ids = KDE_frompickle['ids'] Pk = KDE_frompickle['Pk'] kappa = KDE_frompickle['kappa'] struct = KDE_frompickle['struct'] sampling = KDE_frompickle['sampling'] KDE_method = KDE_frompickle['KDE_method'] fn_in = pyqzt.get_KDE_picklefn(ids, Pk, kappa, struct, sampling, KDE_method) # First things first. Generate the grid plots for all the diagnostics. --------------- discrete_pdf = KDE_frompickle['discrete_pdf'] rsf = KDE_frompickle['rsf'] rsf_keys = KDE_frompickle['rsf_keys'] if do_all_diags: for key in discrete_pdf.keys(): # Reconstruct the line flux mix from the raw rsf data Rval = [] for (r, ratio) in enumerate(key.split('|')[0].split(';')): l1 = ratio.split('/')[0] l2 = ratio.split('/')[1] Rval.append( np.log10(rsf[:, rsf_keys.index(l1)] / rsf[:, rsf_keys.index(l2)])) if save_loc: plot_name = os.path.join( save_loc, fn_in[:-4] + '_' + key.replace('/', '-').replace( ';', '_vs_').replace('|', '_') + '.pdf') else: plot_name = None plot_grid(key.split('|')[0], coeffs=pyqzm.diagnostics[key.split('|')[0]]['coeffs'], Pk=Pk, kappa=kappa, struct=struct, sampling=sampling, color_mode=key.split('|')[1], figname=plot_name, show_plot=show_plots, data=Rval, interp_data=discrete_pdf[key]) # Let's get started with the KDE plot ------------------------------------------------ plt.figure(figsize=(13, 8)) gs = gridspec.GridSpec(2, 2, height_ratios=[0.05, 1.], width_ratios=[1., 1.]) gs.update(left=0.1, right=0.95, bottom=0.1, top=0.9, wspace=0.15, hspace=0.07) ax1 = plt.subplot(gs[1, 0]) ax2 = plt.subplot(gs[1, 1]) # First, the direct estimates -------------------------------------------------------- qzs = KDE_frompickle['qzs'] which_grids = KDE_frompickle['which_grids'] # Create an array to keep track of how big my zoom window will be for ax2 ax2_lims = [np.nan, np.nan, np.nan, np.nan] for (k, key) in enumerate(discrete_pdf.keys()): # Make sure we show each point only once if not (qzs[0] in key): continue # Don't do anything if the point lands outside the plot. if np.isnan(discrete_pdf[key][0]): continue this_diag = key.split('|')[0] for ax in [ax1, ax2]: # The individual realizations ax.scatter(discrete_pdf[this_diag + '|' + qzs[0]][1:], discrete_pdf[this_diag + '|' + qzs[1]][1:], c='k', marker='o', s=1, zorder=2) # Update the zoom-window limits if required ax2_lims = [ np.nanmin( (ax2_lims[0], np.nanmin(discrete_pdf[this_diag + '|' + qzs[0]][1:]))), np.nanmax( (ax2_lims[1], np.nanmax(discrete_pdf[this_diag + '|' + qzs[0]][1:]))), np.nanmin( (ax2_lims[2], np.nanmin(discrete_pdf[this_diag + '|' + qzs[1]][1:]))), np.nanmax( (ax2_lims[3], np.nanmax(discrete_pdf[this_diag + '|' + qzs[1]][1:]))), ] # The direct estimate ax.plot(discrete_pdf[this_diag + '|' + qzs[0]][0], discrete_pdf[this_diag + '|' + qzs[1]][0], c='w', marker='s', markeredgewidth=1.5, markerfacecolor='w', markeredgecolor='k', markersize=11, zorder=10) grid_number = which_grids.index(this_diag) + 1 ax.text(discrete_pdf[this_diag + '|' + qzs[0]][0], discrete_pdf[this_diag + '|' + qzs[1]][0], grid_number, size=12, ha='center', va='center', zorder=11, color='k') if ax == ax1: # And also add the name of the diagnostic ax.text(pyqzm.QZs_lim[pyqzm.M_version][qzs[0]][0] + 0.05, pyqzm.QZs_lim[pyqzm.M_version][qzs[1]][1] - 0.05 * grid_number, '%i: %s' % (grid_number, this_diag), horizontalalignment='left', verticalalignment='center') # Now, plot the global KDE and the associated contours ------------------------------- all_gridZ = KDE_frompickle['all_gridZ'] gridX = KDE_frompickle['gridX'] gridY = KDE_frompickle['gridY'] final_data = KDE_frompickle['final_data'] final_cols = KDE_frompickle['final_cols'] # Loop through all reconstructed KDEs. Plot all the contours, but only the full KDE. kde = False for gridZ_key in all_gridZ.keys(): # If it is just some nans, go no further if np.all(np.isnan(all_gridZ[gridZ_key])): continue # Careful here: gridZ has a weird arrangement ... gridZ = np.rot90(all_gridZ[gridZ_key])[::-1, :] for ax in [ax1, ax2]: if gridZ_key == 'all': my_c = 'darkorange' my_c2 = 'none' my_lw = 2.5 my_zo = 7 # Plot the KDE kde = ax.imshow(gridZ, extent=[ pyqzm.QZs_lim[pyqzm.M_version][qzs[0]][0], pyqzm.QZs_lim[pyqzm.M_version][qzs[0]][1], pyqzm.QZs_lim[pyqzm.M_version][qzs[1]][0], pyqzm.QZs_lim[pyqzm.M_version][qzs[1]][1], ], cmap=pyqzm.pyqz_cmap_1, origin='lower', zorder=0, interpolation='nearest') else: my_c = 'royalblue' my_c2 = 'none' my_lw = 1.5 my_zo = 3 # Plot the contour (two times for the look) # Mind the fact that gridX and gridY refer to the "un-derotated" gridZ ! kde_cont = ax.contour(gridX, gridY, all_gridZ[gridZ_key], [pyqzm.PDF_cont_level], colors=my_c, linestyles='-', linewidths=my_lw, zorder=my_zo) # Plot the individual and global KDE estimates ------------------------------- if gridZ_key == 'all': final_keys = [ '<' + qzs[0] + '{KDE}>', 'err(' + qzs[0] + '{KDE})', '<' + qzs[1] + '{KDE}>', 'err(' + qzs[1] + '{KDE})' ] else: final_keys = [ gridZ_key + '|' + qzs[0] + '{KDE}', 'err(' + gridZ_key + '|' + qzs[0] + '{KDE})', gridZ_key + '|' + qzs[1] + '{KDE}', 'err(' + gridZ_key + '|' + qzs[1] + '{KDE})' ] mean_est = [ final_data[final_cols.index(final_keys[0])], final_data[final_cols.index(final_keys[2])] ] err_est = [ final_data[final_cols.index(final_keys[1])], final_data[final_cols.index(final_keys[3])] ] ax.errorbar(mean_est[0], mean_est[1], xerr=err_est[0], yerr=err_est[1], elinewidth=2., ecolor=my_c, capthick=0, zorder=my_zo) ax.plot(mean_est[0], mean_est[1], c=my_c, marker='o', markersize=10, markeredgecolor=my_c, markerfacecolor=my_c2, markeredgewidth=2, zorder=my_zo) # Plot the combined direct estimates ------------------------------------------------- final_keys = [ '<' + qzs[0] + '>', 'std(' + qzs[0] + ')', '<' + qzs[1] + '>', 'std(' + qzs[1] + ')' ] mean_est = [ final_data[final_cols.index(final_keys[0])], final_data[final_cols.index(final_keys[2])] ] err_est = [ final_data[final_cols.index(final_keys[1])], final_data[final_cols.index(final_keys[3])] ] # Only if that value actually exists ! if not (np.any(np.isnan(mean_est))): for ax in [ax1, ax2]: ax.errorbar(mean_est[0], mean_est[1], xerr=err_est[0], yerr=err_est[1], elinewidth=2, ecolor='k', capthick=0, zorder=8) ax.plot(mean_est[0], mean_est[1], '*', c='w', markeredgecolor='k', markeredgewidth=2, markerfacecolor='w', markersize=20, zorder=9) # Very well, finalize the plot now. for ax in [ax1, ax2]: ax.set_xlabel(qzs[0]) ax.grid(True) # Set the left plot to cover the full extent of the qz plane ax1.set_xlim(pyqzm.QZs_lim[pyqzm.M_version][qzs[0]]) ax1.set_ylim(pyqzm.QZs_lim[pyqzm.M_version][qzs[1]]) ax1.set_ylabel(qzs[1]) # Define the limits for the right plot - a zoomed-in version if np.any(np.isnan(ax2_lims)): ax2.set_xlim(pyqzm.QZs_lim[pyqzm.M_version][qzs[0]]) ax2.set_ylim(pyqzm.QZs_lim[pyqzm.M_version][qzs[1]]) else: ax2.set_xlim(ax2_lims[:2]) ax2.set_ylim(ax2_lims[2:]) # Plot the window of the right plot in the left one rectx = [ ax2_lims[0], ax2_lims[1], ax2_lims[1], ax2_lims[0], ax2_lims[0] ] recty = [ ax2_lims[2], ax2_lims[2], ax2_lims[3], ax2_lims[3], ax2_lims[2] ] ax1.plot(rectx, recty, 'k--', lw=1.5, markersize=5, zorder=1) ax2.set_aspect('auto') ax1.set_aspect('auto') ax1.locator_params(axis='x', nbins=5) ax2.locator_params(axis='x', nbins=5) # Plot the colorbar if required if kde: cb_ax = plt.subplot(gs[0, :]) cb = Colorbar(ax=cb_ax, mappable=kde, orientation='horizontal') # Colorbar legend cb.set_label(r'Joint Probability Density (normalized to peak)', labelpad=-60) cb.ax.xaxis.set_ticks_position('top') cb.solids.set_edgecolor('face') # Draw the 1-sigma level (assuming gaussian = 61% of the peak) cb.ax.axvline(x=pyqzm.PDF_cont_level, color='darkorange', linewidth=3, linestyle='-') # Get ready to save this: if save_loc: plot_name = os.path.join(save_loc, fn_in[:-3] + 'pdf') plt.savefig(plot_name, bbox_inches='tight') if show_plots: plt.show() else: plt.close() # ----------------------------------------------------------------------------------------
def diffraction_plot(diffraction, k_values, ax=None, cmap="afmhot", vmin=4e-6, vmax=0.7): """Helper function to plot diffraction pattern. Args: diffraction (:class:`numpy.ndarray`): Diffraction image data. k_values (:class:`numpy.ndarray`): :math:`k` value magnitudes for each bin of the diffraction image. ax (:class:`matplotlib.axes.Axes`): Axes object to plot. If :code:`None`, make a new axes and figure object (Default value = :code:`None`). cmap (str): Colormap name to use (Default value = :code:`'afmhot'`). vmin (float): Minimum of the color scale (Default value = 4e-6). vmax (float): Maximum of the color scale (Default value = 0.7). Returns: :class:`matplotlib.axes.Axes`: Axes object with the diagram. """ import matplotlib.colors from matplotlib.colorbar import Colorbar from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable if ax is None: fig = plt.figure() ax = fig.subplots() # Plot the diffraction image and color bar norm = matplotlib.colors.LogNorm(vmin=vmin, vmax=vmax) im = ax.imshow(np.clip(diffraction, vmin, vmax), interpolation="nearest", cmap=cmap, norm=norm) ax_divider = make_axes_locatable(ax) cax = ax_divider.append_axes("right", size="7%", pad="10%") cb = Colorbar(cax, im) cb.set_label(r"$S(\vec{k})$") # Determine the number of ticks on the axis grid_size = diffraction.shape[0] num_ticks = len( [i for i in ax.xaxis.get_ticklocs() if 0 <= i <= grid_size]) # Ensure there are an odd number of ticks, so that there is a tick at zero num_ticks += 1 - num_ticks % 2 ticks = np.linspace(0, grid_size, num_ticks) # Set tick locations and labels tick_labels = np.interp(ticks, range(grid_size), k_values) tick_labels = [f"{x:.3g}" for x in tick_labels] ax.xaxis.set_ticks(ticks) ax.xaxis.set_ticklabels(tick_labels) ax.yaxis.set_ticks(ticks) ax.yaxis.set_ticklabels(tick_labels) # Set title, limits, aspect ax.set_title("Diffraction Pattern") ax.set_aspect("equal", "datalim") ax.set_xlabel("$k_x$") ax.set_ylabel("$k_y$") return ax
def dynamic_spectra(line, MJD_all, vel_all, flux_all, resolution, vmin, vmax, set_limits, phase_folded, P, t0, velmin, velmax): #resolution = 0.5 #days flx_all = [] temp = np.arange(velmin, velmax, 1) MJD_to_sort = np.array(MJD_all) sort = MJD_to_sort.argsort() MJD_all = np.array(MJD_to_sort)[sort] #flag_all = np.array(flag_all)[sort] vel_all = np.array(vel_all)[sort] flux_all = np.array(flux_all)[sort] #print(len(MJD_all)) #print(vel_all) #print(flux_all) for i in range(len(flux_all)): # interpolates specrum on 'temp' so they all have the same size :) flx = griddata(vel_all[i], flux_all[i], temp, method='linear') #plt.plot(vel_all[i], flux_all[i], linewidth=0.4, label=MJD_all[i]) flx_all.append(flx) #print(flx_all) flxx = np.array(flx_all) keep = np.logical_not(np.isnan(flx_all))[:, 0] flx_all = flxx[keep] vel_all = vel_all[keep] MJD_all = MJD_all[keep] MJD_to_sort = np.array(MJD_all) sort = MJD_to_sort.argsort() #plt.legend() #plt.show() #print(len(MJD_all)) #im so good at names hello = np.mean(flx_all, axis=0) supes = [] for j in range(len(flx_all)): #superflux = np.tile(flx_all[j]-hello, (1, 1)) superflux = flx_all[j] - hello #superflux = np.tile(flx_all[j], (1, 1)) #supes.append((superflux+ 1)**3 - 1) supes.append(superflux) #flux_a = np.tile(flx_all[0], (1, 1)) MJD_a = MJD_all[sort] #print(len(MJD_a), len(MJD_all)) MJD_a = MJD_a - min(MJD_a) MJD_keep = np.copy(MJD_a) phase = (MJD_a - t0) / P % 1 phase_keep = np.copy(phase) #ic(phase_keep) if not phase_folded: MJD_a = MJD_a / resolution size_time = np.arange(MJD_a.min(), MJD_a.max(), 1) print(len(size_time)) print(size_time) master = np.zeros([len(size_time), len(hello)]) data_positions = [] for k in range(len(MJD_a)): data_pos = int(MJD_a[k]) data_positions.append(data_pos) pos_breakdown = list(set(data_positions)) for final_pos in pos_breakdown: pos = np.where(np.array(data_positions) == final_pos)[0] flx_pos = np.sum(np.array(supes)[pos], axis=0) / len(pos) master[final_pos] = flx_pos # s_master=np.zeros([93, len(hello)]) # MJD_norm = normalize(MJD_keep) # #MJD_range = np.arange(MJD_keep[0], MJD_keep[-1], 96) # for cc in range(0,93): # MJD_range = [0.01*cc, 0.01*cc+ 0.08] # ic(MJD_range) # s_mask = np.ma.masked_inside(MJD_norm, MJD_range[0], MJD_range[1]).mask # ic(MJD_keep[s_mask]) # s_flx_pos = np.sum(np.array(supes)[s_mask], axis=0)/len(np.array(supes)[s_mask]) # s_master[cc] = s_flx_pos # master = np.copy(s_master) set_time_limits = [MJD_all.max(), MJD_all.min()] set_time_label = 'MJD' else: phase = phase / resolution size_time = np.arange(phase.min(), phase.max(), 1) #size_time = np.concatenate([size_time])#, [phase.max()]]) size_time = size_time - int(phase.min()) #print(len(size_time)) #print(size_time) master = np.zeros([len(size_time), len(hello)]) data_positions = [] for k in range(len(phase)): data_pos = int(phase[k]) - int(phase.min()) data_positions.append(data_pos) pos_breakdown = list(set(data_positions)) for final_pos in pos_breakdown: pos = np.where(np.array(data_positions) == final_pos)[0] flx_pos = np.sum(np.array(supes)[pos], axis=0) / len(pos) master[final_pos] = flx_pos s_master = np.zeros([93, len(hello)]) for cc in range(0, 93): phase_range = [0.01 * cc, 0.01 * cc + 0.08] #ic(phase_range) s_mask = np.ma.masked_inside(phase_keep, phase_range[0], phase_range[1]).mask #ic(phase_keep[s_mask]) s_flx_pos = np.sum(np.array(supes)[s_mask], axis=0) / len( np.array(supes)[s_mask]) s_master[cc] = s_flx_pos #print(len(master)) # 2 phases master = np.tile(s_master, (2, 1)) #print(len(master)) set_time_limits = [2, 0] set_time_label = 'Phase (P = {:.2f})'.format(P) masked_array = np.ma.masked_where(master == 0, master) #my_cmap = mpl.cm.viridis my_cmap = copy.copy(mpl.cm.get_cmap("viridis")) my_cmap.set_bad(color='white') fig = plt.figure(1, figsize=(4, 8)) gs1 = gridspec.GridSpec(4, 1, height_ratios=[0.05, 0.15, 1, 0.2]) gs1.update(hspace=0.00, wspace=0.025) #, top=0.9) #fig.subplots_adjust(right=0.8) ax = plt.subplot(gs1[2, 0]) #cbax = fig.add_axes([.85, 0.25, 0.03, 0.5]) if set_limits: img1 = ax.imshow( masked_array, cmap=my_cmap, interpolation='nearest', extent=[velmin, velmax, set_time_limits[0], set_time_limits[1]], aspect='auto', vmin=vmin, vmax=vmax) else: img1 = ax.imshow( masked_array, cmap=my_cmap, interpolation='nearest', extent=[velmin, velmax, set_time_limits[0], set_time_limits[1]], aspect='auto') ax_divider = make_axes_locatable(ax) # add an axes above the main axes. cbax = ax_divider.append_axes("top", size="5%", pad="2%") #cb = colorbar(im2, cax=cax2, orientation="horizontal") cb = Colorbar(ax=cbax, mappable=img1, orientation='horizontal', ticklocation='top') cb.set_label('Relative flux', fontsize=11) #cb.set_clim(-0.1, 0.1) plt.setp(ax.get_xticklabels(), visible=False) ax.set_ylabel(set_time_label) #ax.set_title(line) t = np.linspace(0., 2., 100) X2 = np.linspace(np.pi / 2, 4.5 * np.pi, 100) sine = np.sin(X2) amp = 55.9 #ax.plot(amp*sine, t, color='xkcd:darkish red', lw=0.6) #amp=4. #ax.plot(amp*sine, t, color='xkcd:strawberry', lw=0.6) #temp2 = np.arange(-850, +850, 0.2) # #ax1 = plt.subplot(gs1[2, 1]) # # #for k in range(len(master)): # #for l in range(len(MJD_a)): # plt.scatter(temp, 4*master[k]+MJD_all[k], c=master[k], cmap=my_cmap, s=0.5) #ax1.set_ylim(ax1.get_ylim()[::-1]) ax2 = plt.subplot(gs1[3, 0]) ax2.set_ylabel('Norm. flux', fontsize=9) ax2.set_xlabel('$\mathrm{Velocity\,[km\,s^{-1}]}$') nbins = 4 ax.yaxis.set_major_locator(MaxNLocator(nbins=8, prune='upper')) ax2.yaxis.set_major_locator(MaxNLocator(nbins=nbins, prune='upper')) hello = np.mean(flx_all, axis=0) #new_color = plt.cm.jet(phase_keep) #print(new_color) for flxs in flx_all: ax2.plot(temp, flxs, color='gray', alpha=0.3, lw=0.5) ax2.plot(temp, hello, color=my_cmap(.25), lw=2) ax2.set_xlim(velmin, velmax) #ax2.set_ylim(0., 4.) #ax.axvline(-200, ls=':', color='k', lw=0.5) #ax.axvline(200, ls=':', color='k', lw=0.5) #ax2.axvline(-200, ls=':', color='k', lw=0.5) #ax2.axvline(200, ls=':', color='k', lw=0.5) #ax.yaxis.grid(False) # Hide the horizontal gridlines #ax2.yaxis.grid(False) # Hide the horizontal gridlines #ax.xaxis.grid(True) # Show the vertical gridlines #ax2.xaxis.grid(True) # Show the vertical gridlines plt.savefig(line + "_dynamic_s.pdf", dpi=100, bbox_inches='tight')
def plotProfDist_in_BoundingBox(df, boundingBox=[], var='CTEMP', wd=7.48, ht=5, varmin=-2, varmax=5, levs=[], show=True, plotEcho=False, xlat=False, colorunit='$\\theta^{\circ}$C ', save=False, savename="Untitled.png", fontsize=8, levels=[], zmin=0.0, ticks=[], cline=[], legend_show=True, plotTimeHist=False): matplotlib.rcParams.update({'font.size': fontsize}) plt.close(1) fig = plt.figure(1, figsize=(wd, ht)) gs = gridspec.GridSpec(2, 1, height_ratios=[1, 0.05]) ax = plt.subplot(gs[0, 0]) if not boundingBox: raise ValueError( 'provide arg boundingBox in fmt [[llcornerx, llcornery], [urcrnrx, urcrnry]] \n With x1,y1 being lower left corner of bounding box, and going counter-clockwise from that point.' ) try: leftlonlim = boundingBox[0][0] rightlonlim = boundingBox[1][0] lowerlatlim = boundingBox[0][1] upperlatlim = boundingBox[1][1] except: raise ValueError( 'provide arg boundingBox in fmt [[x1,y1], [x2, y2], [x3, y3], [x4, y4]] \n With x1,y1 being lower left corner of bounding box, and going counter-clockwise from that point.' ) selectProfiles = (df.LATITUDE >= lowerlatlim) & ( df.LATITUDE <= upperlatlim) & (df.LONGITUDE >= leftlonlim) & ( df.LONGITUDE <= rightlonlim) & (~df.CTEMP.isnull()) if xlat: dist = df.loc[selectProfiles, 'LATITUDE'] else: dist = df.loc[selectProfiles, 'DIST_GLINE'] depth = df.loc[selectProfiles, 'DEPTH'] gamman = df.loc[selectProfiles, 'gamman'] if xlat: ndist = int((np.max(dist) - np.min(dist)) / 0.01) else: ndist = int(df.loc[selectProfiles, 'DIST_GLINE'].max() / 10.) dist_grid = np.linspace(np.min(dist), np.max(dist), ndist) ndepth = int(np.abs(df.loc[selectProfiles, 'DEPTH'].min()) / 10.) depth_grid = np.linspace(df.loc[selectProfiles, 'DEPTH'].min(), 0, ndepth) gamman_interpolated = mlab.griddata(dist, depth, gamman, dist_grid, depth_grid, interp='linear') cs = ax.scatter(dist, df.loc[selectProfiles, 'DEPTH'], c=df.loc[selectProfiles, 'CTEMP']) if levels: cs_gamman = ax.contour(dist_grid, depth_grid, gamman_interpolated, levels, colors='0.5') else: cs_gamman = ax.contour(dist_grid, depth_grid, gamman_interpolated, colors='0.5') distSortedIndices = np.argsort(df.loc[selectProfiles, 'DIST_GLINE']) if plotEcho: depthMin = df.loc[selectProfiles].groupby( pd.cut(df.loc[selectProfiles].DIST_GLINE, dist_grid))[["DEPTH"]].min(axis=1).values echodepthMin = df.loc[selectProfiles].groupby( pd.cut(df.loc[selectProfiles].DIST_GLINE, dist_grid))[["ECHODEPTH"]].min(axis=1).values min_of_depth_echodepth = np.array(list(zip(depthMin, echodepthMin))).min(axis=1) ax.plot(dist_grid[:-1], min_of_depth_echodepth, linewidth=4, color='k') #ax.set_xlim(df.loc[selectProfiles, 'DIST_GLINE'].min()-1, df.loc[selectProfiles, 'DIST_GLINE'].max()+1) if not cline: cline = np.arange(27.8, 28.5, 0.1) ax.clabel(cs_gamman, colors='k', fontsize=14, fmt='%3.2f') colorax = plt.subplot(gs[1, 0]) cbar1 = Colorbar(ax=colorax, mappable=cs, orientation='horizontal') cbar1.ax.get_children()[0].set_linewidths(5) cbar1.set_label(colorunit) if plotTimeHist: plt.close(2) fig = plt.figure(2, figsize=(wd, ht)) uniqueProfs = df.loc[selectProfiles].groupby("PROFILE_NUMBER").head( 1).index df.loc[uniqueProfs, "JULD"].hist() plt.show() if save: plt.savefig(savename, dpi=300) if show: plt.show()
beam.set_facecolor('w') ax.add_artist(beam) # limits, labeling ax.set_xlim(dRA_lims) ax.set_ylim(dDEC_lims) ax.set_xlabel('RA offset ($^{\prime\prime}$)') ax.set_ylabel('DEC offset ($^{\prime\prime}$)') # add a scalebar cbax = fig.add_subplot(gs[:, 1]) cb = Colorbar(ax=cbax, mappable=im, orientation='vertical', ticklocation='right') cb.set_label('brightness temperature (K)', rotation=270, labelpad=22) # adjust layout fig.subplots_adjust(wspace=0.02) fig.subplots_adjust(left=0.11, right=0.89, bottom=0.1, top=0.98) fig.savefig('../figs/' + target + '_dataimage.pdf') ### - REMOVE THE AZIMUTHAL ASYMMETRY if rm_az: print('....') print('Removing azimuthal asymmetry') print('....') geom = disk.disk[target]['incl'], disk.disk[target]['PA'], \ disk.disk[target]['dx'], disk.disk[target]['dy'] remove_arc(target, geom,
def voronoi_plot(box, polytopes, ax=None, color_by_sides=True, cmap=None): """Helper function to draw 2D Voronoi diagram. Args: box (:class:`freud.box.Box`): Simulation box. polytopes (:class:`numpy.ndarray`): Array containing Voronoi polytope vertices. ax (:class:`matplotlib.axes.Axes`): Axes object to plot. If :code:`None`, make a new axes and figure object. (Default value = :code:`None`). color_by_sides (bool): If :code:`True`, color cells by the number of sides. If :code:`False`, random colors are used for each cell. (Default value = :code:`True`). cmap (str): Colormap name to use (Default value = :code:`None`). Returns: :class:`matplotlib.axes.Axes`: Axes object with the diagram. """ from matplotlib import cm from matplotlib.collections import PatchCollection from matplotlib.patches import Polygon from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable from matplotlib.colorbar import Colorbar if ax is None: fig = Figure() ax = fig.subplots() # Draw Voronoi polytopes patches = [Polygon(poly[:, :2]) for poly in polytopes] patch_collection = PatchCollection(patches, edgecolors='black', alpha=0.4) if color_by_sides: colors = np.array([len(poly) for poly in polytopes]) num_colors = np.ptp(colors) + 1 else: colors = np.random.RandomState().permutation(np.arange(len(patches))) num_colors = np.unique(colors).size # Ensure we have enough colors to uniquely identify the cells if cmap is None: if color_by_sides and num_colors <= 10: cmap = 'tab10' else: if num_colors > 20: warnings.warn('More than 20 unique colors were requested. ' 'Consider providing a colormap to the cmap ' 'argument.', UserWarning) cmap = 'tab20' cmap = cm.get_cmap(cmap, num_colors) bounds = np.arange(np.min(colors), np.max(colors)+1) patch_collection.set_array(np.array(colors)-0.5) patch_collection.set_cmap(cmap) patch_collection.set_clim(bounds[0]-0.5, bounds[-1]+0.5) ax.add_collection(patch_collection) # Draw box corners = [[0, 0, 0], [0, 1, 0], [1, 1, 0], [1, 0, 0]] # Need to copy the last point so that the box is closed. corners.append(corners[0]) corners = box.make_absolute(corners)[:, :2] ax.plot(corners[:, 0], corners[:, 1], color='k') # Set title, limits, aspect ax.set_title('Voronoi Diagram') ax.set_xlim((np.min(corners[:, 0]), np.max(corners[:, 0]))) ax.set_ylim((np.min(corners[:, 1]), np.max(corners[:, 1]))) ax.set_aspect('equal', 'datalim') # Add colorbar for number of sides if color_by_sides: ax_divider = make_axes_locatable(ax) cax = ax_divider.append_axes("right", size="7%", pad="10%") cb = Colorbar(cax, patch_collection) cb.set_label("Number of sides") cb.set_ticks(bounds) return ax
ax.text(dRA_lims[0] + 0.04 * np.diff(dRA_lims), dDEC_lims[1] - 0.10 * np.diff(dDEC_lims), disk_lbls[i], color='k', fontsize=6) ax.set_xlim(dRA_lims) ax.set_ylim(dDEC_lims) if (i == 4): ax.set_xlabel('RA offset ($^{\prime\prime}$)') ax.set_ylabel('DEC offset ($^{\prime\prime}$)', labelpad=0.5) ax.set_xticks([1, 0, -1]) ax.set_yticks([-1, 0, 1]) else: ax.set_xticks([]) ax.set_yticks([]) # colorbar cbax = fig.add_axes( [right + 0.01, bottom, 0.02, 0.5 * (top + bottom) - bottom]) cb = Colorbar(ax=cbax, mappable=im, orientation='vertical', ticklocation='right', ticks=[-10, -8, -6, -4, -2, 0, 2, 4, 6, 8, 10]) cb.set_label('residual S/N', rotation=270, labelpad=8) # adjust full figure layout fig.subplots_adjust(wspace=wspace, hspace=hspace) fig.subplots_adjust(left=left, right=right, bottom=bottom, top=top) fig.savefig('../../figs/geom_test2.pdf')
cordy = cordy /1e+3 filename_counter = 0 for i in np.arange(len(magnitude1)): fig = plt.figure(figsize =(4.1,4.1)) gs = fig.add_gridspec(28,28) ax_cb = plt.subplot(gs[0:12,13]) ax_map = plt.subplot(gs[0:12,1:13]) ax_UWD = plt.subplot(gs[17:22,1:-1]) ax_SDH = plt.subplot(gs[23:,1:-1]) cf = ax_map.contourf(X,Y,uztot[i,:,:],levels = np.linspace(np.min(uztot),0,30)) cb = Colorbar(ax = ax_cb, mappable = cf,ticks = np.linspace(np.min(uztot),0,5)) cbar_label = np.round(np.linspace(np.min(uztot),0,5)*10)/10 cb.ax.set_yticklabels(cbar_label,fontsize = 6 ) cb.set_label('Vert. Displacement [m]',fontsize = 8 ) ax_map.set_xticks([np.min(X),0,np.max(X)]) ax_map.set_yticks([np.min(Y),0,np.max(Y)]) ax_map.set_xlabel('x [km]',fontsize = 8 ) ax_map.set_ylabel('y [km]', fontsize = 8) ax_map.set_xticklabels(labels = [int(np.min(X)),int(0),int(np.max(X))], fontsize = 6) ax_map.set_yticklabels(labels = [int(np.min(Y)),0,int(np.max(Y))], fontsize = 6) h1 = [] h2 = [] names_st = ['ST1','ST2'] for j in np.arange(len(cordx)): x = cordx[j] y = cordy[j]
color='w', fontsize=6) ax.set_xlim(dRA_lims) ax.set_ylim(dDEC_lims) ax.set_yticks([-0.5, 0.0, 0.5]) if (i == 4) and (j == 0): ax.set_xlabel('RA offset ($^{\prime\prime}$)', labelpad=2) ax.set_ylabel('DEC offset ($^{\prime\prime}$)', labelpad=-3) ax.tick_params(axis='y', length=1.5) ax.tick_params(axis='x', length=2) else: ax.set_xticklabels([]) ax.set_yticklabels([]) ax.axis('off') ### Colormap scalebar cbax = fig.add_subplot(gs[i, 3]) cbax.tick_params(axis='y', length=2) cb = Colorbar(ax=cbax, mappable=im, orientation='vertical', ticklocation='right', ticks=Tbticks[i]) if (i == 4): cb.set_label('$T_b$ (K)', rotation=270, labelpad=6) # adjust full figure layout fig.subplots_adjust(wspace=wspace, hspace=hspace) fig.subplots_adjust(left=left, right=right, bottom=bottom, top=top) fig.savefig('../figs/dmrs1.pdf')