def plotPanel(sX, sY, gX, gY, xMin, xMax, yMin, yMax, xLabel, yLabel, title=''): ## bin (astroML code) # axes limits range = np.zeros((2,2)) range[0,0]=xMin range[0,1]=xMax range[1,0]=yMin range[1,1]=yMax NS, xedgesS, yedgesS = binned_statistic_2d(sX, sY, sY,'count', bins=20, range=range) NG, xedgesG, yedgesG = binned_statistic_2d(gX, gY, gY,'count', bins=20, range=range) ## plot ## galaxies are blue contours levels = np.linspace(0, np.log10(NG.max()), 7)[2:] # plt.contour(np.log10(NG.T), levels, colors='b', linewidths=2, extent=[xedgesG[0], xedgesG[-1], yedgesG[0], yedgesG[-1]]) plt.scatter(gX, gY, color='blue', s=5, linewidths=1, alpha=0.2) # stars are copper continuous map cmap = plt.cm.copper cmap.set_bad('w', 0.0) # plt.imshow(np.log10(NS.T), origin='lower', extent=[xedgesS[0], xedgesS[-1], yedgesS[0], yedgesS[-1]], aspect='auto', interpolation='nearest', cmap=cmap) plt.scatter(sX, sY, color='red', s=10, linewidths=1, alpha=0.25) plt.xlim(xMin, xMax) plt.ylim(yMin, yMax) plt.xlabel(xLabel, fontsize=16) plt.ylabel(yLabel, fontsize=16) xTitle = xMin + 0.05*(xMax-xMin) yTitle = yMax + 0.05*(yMax-yMin) ax.text(xTitle, yTitle, title)
def new_moving_average(x_arr, y_arr, z_arr, mask, mass_interval_dict, mass_name, x_bins=3, y_bins=8, step=5, x_lim=(9, 12), y_lim=(-13, -9), num_thres=2): from astroML.stats import binned_statistic_2d for num in range(0, step-1): forward = ((y_lim[0] - y_lim[1]) / y_bins) / (step - 1) * num z_stats1, x_edges, y_edges = binned_statistic_2d( x_arr, y_arr, z_arr, 'count', bins=(np.linspace(x_lim[0], x_lim[1], x_bins + 1), np.linspace(y_lim[0] + forward, y_lim[1] + forward, y_bins + 1))) z_stats2, x_edges, y_edges = binned_statistic_2d( x_arr[mask], y_arr[mask], z_arr[mask], 'count', bins=(np.linspace(x_lim[0], x_lim[1], x_bins + 1), np.linspace(y_lim[0] + forward, y_lim[1] + forward, y_bins + 1))) z_stats = z_stats2 / z_stats1 number_mask = z_stats1[mass_interval_dict[mass_name]] <= num_thres if num == 0: x_stacks = (y_edges[:-1] + y_edges[1:]) / 2 y_stacks = z_stats[mass_interval_dict[mass_name]] y_stacks[number_mask] = np.nan # Binomial Error # r = 0.842 err_stacks = r * np.sqrt(z_stats[mass_interval_dict[mass_name]] * (1 - z_stats[mass_interval_dict[mass_name]]) / z_stats1[mass_interval_dict[mass_name]]) err_stacks[number_mask] = np.nan else: x_stacks = np.vstack([x_stacks, (y_edges[:-1] + y_edges[1:]) / 2]) y = z_stats[mass_interval_dict[mass_name]] y[number_mask] = np.nan y_stacks = np.vstack([y_stacks, y]) # Binomial Error # err = r * np.sqrt(z_stats[mass_interval_dict[mass_name]] * (1 - z_stats[mass_interval_dict[mass_name]]) / z_stats1[mass_interval_dict[mass_name]]) err[number_mask] = np.nan err_stacks = np.vstack([err_stacks, err]) return x_stacks, y_stacks, err_stacks
def test_2d_median(): x = np.random.random(100) y = np.random.random(100) v = np.random.random(100) stat1, binx1, biny1 = binned_statistic_2d(x, y, v, 'median', bins=5) stat2, binx2, biny2 = binned_statistic_2d(x, y, v, np.median, bins=5) assert_array_almost_equal(stat1, stat2) assert_array_almost_equal(binx1, binx2) assert_array_almost_equal(biny1, biny2)
def plot_cc(group, ax, x_bands, y_bands, meta_property=None, theta_property=None, ml_band=None, values=None, xlim=None, ylim=None, statistic='median', bins=100, cmap=mpl.cm.cubehelix, value_func=None, hist_func=None, x_label_pad=None, y_label_pad=None, vmin=None, vmax=None): x = get_colour(group, x_bands) y = get_colour(group, y_bands) if xlim is not None and ylim is not None: # [[xmin, xmax], [ymin, ymax]] rng = [[xlim[0], xlim[-1]], [ylim[0], ylim[-1]]] else: rng = None # Get the property to use for the binned statistic, if any if meta_property is not None: values = group['meta'][meta_property] elif theta_property is not None: values = group['params'][theta_property] elif ml_band is not None: values = group['mass_light'][ml_band] elif values is not None: assert len(values) == len(x) else: values = None if value_func is not None: values = value_func(values) H, x_edges, y_edges = binned_statistic_2d(x, y, values, statistic=statistic, bins=bins, range=rng) print x_edges[0], x_edges[-1] print y_edges[0], y_edges[-1] if hist_func is not None: H = hist_func(H) im = ax.imshow(H.T, origin='lower', aspect='auto', cmap=cmap, interpolation='nearest', vmin=vmin, vmax=vmax, extent=[x_edges[0], x_edges[-1], y_edges[0], y_edges[-1]]) ax.set_xlim(x_edges[0], x_edges[-1]) ax.set_ylim(y_edges[0], y_edges[-1]) xlabel = r"${0} - {1}$".format(latex_name(x_bands[0], mathmode=False), latex_name(x_bands[-1], mathmode=False)) ax.set_xlabel(xlabel, labelpad=x_label_pad) ylabel = r"${0} - {1}$".format(latex_name(y_bands[0], mathmode=False), latex_name(y_bands[-1], mathmode=False)) ax.set_ylabel(ylabel, labelpad=y_label_pad) return im
def plot_mass_met_table(self, opt_mass_met_file, ir_mass_met_file, extra_str=''): from mpl_toolkits.axes_grid1 import ImageGrid from astroML.stats import binned_statistic_2d fig = plt.figure(figsize=(8, 8)) grid = ImageGrid(fig, 111, nrows_ncols=(2, 2), axes_pad=.5, add_all=True, label_mode="all", cbar_location="top", cbar_mode="each", cbar_size="7%", cbar_pad="2%", aspect=0) cmaps = [plt.cm.get_cmap('jet', 9), plt.cm.gray_r] #cmap = #cmap.set_bad('w', 1.) #fig, (axs) = plt.subplots(ncols=2, figsize=(8, 8), sharey=True) types = ['mean', 'count'] k =-1 for j in range(len(types)): for i, mass_met in enumerate([opt_mass_met_file, ir_mass_met_file]): k += 1 with open(mass_met, 'r') as mmf: lines = [l.strip() for l in mmf.readlines() if not l.startswith('#')] mag = np.concatenate([np.array(l.split(), dtype=float) for l in lines[0::3]]) mass = np.concatenate([np.array(l.split(), dtype=float) for l in lines[1::3]]) mh = np.concatenate([np.array(l.split(), dtype=float) for l in lines[2::3]]) N, xedges, yedges = binned_statistic_2d(mag, mass, mh, types[j], bins=50) im = grid[k].imshow(N.T, origin='lower', extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]], aspect='auto', interpolation='nearest', cmap=cmaps[j]) grid[k].cax.colorbar(im) #grid[i].cax.set_label('$[M/H]$') grid.axes_all[0].set_ylabel('${\\rm Mass}\ (M_\odot)$', fontsize=20) grid.axes_all[2].set_ylabel('${\\rm Mass}\ (M_\odot)$', fontsize=20) grid.axes_all[2].set_xlabel('$F814W$', fontsize=20) grid.axes_all[3].set_xlabel('$F160W$', fontsize=20) target = '_'.join(os.path.split(opt_mass_met_file)[1].split('_')[0:4]) fig.suptitle('$%s$' % target.replace('_', '\ '), fontsize=20) plt.savefig('%s_mass_met%s.png' % (target, extra_str), dpi=150) return grid
def test_2d_count(): x = np.random.random(100) y = np.random.random(100) v = np.random.random(100) count1, binx1, biny1 = binned_statistic_2d(x, y, v, 'count', bins=5) count2, binx2, biny2 = np.histogram2d(x, y, bins=5) assert_array_almost_equal(count1, count2) assert_array_almost_equal(binx1, binx2) assert_array_almost_equal(biny1, biny2)
def test_2d_sum(): x = np.random.random(100) y = np.random.random(100) v = np.random.random(100) sum1, binx1, biny1 = binned_statistic_2d(x, y, v, 'sum', bins=5) sum2, binx2, biny2 = np.histogram2d(x, y, bins=5, weights=v) assert_array_almost_equal(sum1, sum2) assert_array_almost_equal(binx1, binx2) assert_array_almost_equal(biny1, biny2)
def pdf_plot(self, xcol, ycol, zcol, stat='median', bins='uniq', log=False, cbar=True, inds=None, ax=None, vmin=None, vmax=None): try: from astroML.stats import binned_statistic_2d except ImportError: print('need astroML.stats.binned_statistic_2d for this function') return -1 if inds is None: inds = np.arange(len(self.data[xcol])) if bins == 'uniq': bins=[np.unique(self.data[xcol][inds]), np.unique(self.data[ycol][inds])] N, xe, ye = binned_statistic_2d(self.data[xcol][inds], self.data[ycol][inds], self.data[zcol][inds], stat, bins=bins) if log is True: n = np.log10(N.T) else: n = N.T aspect = (xe[-1] - xe[0]) / (ye[-1] - ye[0]) if ax is None: fig, ax = plt.subplots() im = ax.imshow(n, extent=[xe[0], xe[-1], ye[0], ye[-1]], vmin=vmin, vmax=vmax, cmap=plt.cm.Blues_r, aspect=aspect, interpolation='nearest') ax.set_xlabel(key2label(xcol), fontsize=16) ax.set_ylabel(key2label(ycol), fontsize=16) if cbar: cb = plt.colorbar(im) if callable(stat): stat = stat.__name__ cb.set_label(r'$\rm{%s}$\ %s' % (stat, key2label(zcol))) ax = (ax, cb) return ax
def bs2d(self, x, y, z, stat='count', bins='default'): """ call astroML.binned_statistic_2d if bins == 'default' will send unique values of x and y as bins see astroML.binned_statistic_2d doc Parameters ---------- x, y, z : array or string arrays or names of data arrays to send to binned_statistic_2d """ x = self.get_val(x) y = self.get_val(y) z = self.get_val(z) if bins == 'default': bins = [np.unique(x), np.unique(y)] return binned_statistic_2d(x, y, z, stat, bins=bins)
def completeness_hess(self, fieldnum, band, x_mag, y_mag, xlim, ylim, dmag): """Make a Hess diagram of completeness acros the plane.""" label = self.fields[fieldnum]['label'] s = np.where(self.labels == label)[0] tt = self.t[s] if isinstance(y_mag, basestring): # a single mag y = tt[self.band_key_in(y_mag)] else: b1, b2 = y_mag y = tt[self.band_key_in(b1)] - tt[self.band_key_in(b2)] if isinstance(x_mag, basestring): # a single mag x = tt[self.band_key_in(x_mag)] else: b1, b2 = x_mag x = tt[self.band_key_in(b1)] - tt[self.band_key_in(b2)] # bin the number of stars into the hess plane and the number of # recovered stars to get the completeness fraction def _completeness(values): v = np.array(values) if len(v) == 0: return np.nan else: return float(np.where(v < 90.)[0].shape[0]) / v.shape[0] # extend stop so it is included; len(edges) is nx+1 x_grid = np.arange(min(xlim), max(xlim) + dmag / 2., dmag) y_grid = np.arange(min(ylim), max(ylim) + dmag / 2., dmag) H, x_edges, y_edges = binned_statistic_2d(x, y, tt[self.band_key_out(band)], statistic=_completeness, bins=[x_grid, y_grid]) return H.T, x_edges, y_edges
def error_hess(self, fieldnum, band, x_mag, y_mag, xlim, ylim, dmag): """Make a Hess diagram of the mean error across the Hess plane.""" label = self.fields[fieldnum]['label'] s = np.where(self.labels == label)[0] tt = self.t[s] if isinstance(y_mag, basestring): # a single mag y = tt[self.band_key_in(y_mag)] else: b1, b2 = y_mag y = tt[self.band_key_in(b1)] - tt[self.band_key_in(b2)] if isinstance(x_mag, basestring): # a single mag x = tt[self.band_key_in(x_mag)] else: b1, b2 = x_mag x = tt[self.band_key_in(b1)] - tt[self.band_key_in(b2)] # extend stop so it is included; len(edges) is nx+1 x_grid = np.arange(min(xlim), max(xlim) + dmag / 2., dmag) y_grid = np.arange(min(ylim), max(ylim) + dmag / 2., dmag) diff = tt[self.band_key_in(band)] - tt[self.band_key_out(band)] def filtered_sigma(vals): """Filter out the dropped stars from sigma computation.""" s = np.where(np.abs(vals) < 20.)[0] return np.std(vals[s]) H, x_edges, y_edges = binned_statistic_2d(x, y, diff, statistic=filtered_sigma, bins=[x_grid, y_grid]) return H.T, x_edges, y_edges
'age_fact': age_fact} return pagb_cmd, pagb_kwargs from astroML.stats import binned_statistic_2d for j in range(len(types)): for i, mass_met in enumerate([opt_mass_met_file, ir_mass_met_file]): k += 1 with open(mass_met, 'r') as mmf: lines = [l.strip() for l in mmf.readlines() if not l.startswith('#')] mag = np.concatenate([np.array(l.split(), dtype=float) for l in lines[0::3]]) mass = np.concatenate([np.array(l.split(), dtype=float) for l in lines[1::3]]) mh = np.concatenate([np.array(l.split(), dtype=float) for l in lines[2::3]]) N, xedges, yedges = binned_statistic_2d(mag, mass, mh, types[j], bins=50) im = grid[k].imshow(N.T, origin='lower', extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]], aspect='auto', interpolation='nearest', cmap=cmaps[j]) grid[k].cax.colorbar(im) #grid[i].cax.set_label('$[M/H]$')
def start(): direktorij=output_folder.get() if not os.path.exists(direktorij): os.makedirs(direktorij) finishing_string='Name & Mean & Median\\\\ \n' starting_list=['Name','Mean','Median'] finishing_list=[] f.seek(0) textval=[a.get() for a in txtv] textu=[a.get() for a in txtu] textl=[a.get() for a in txtl] labele=OrderedDict([(textval[j],j) for j in range(len(textval)) if(len(textval[j])!=0)]) labeleu=OrderedDict([(textval[j],float(textu[j])) for j in range(len(textval)) if((len(textu[j])!=0) and (len(textval[j])!=0))]) labelel=OrderedDict([(textval[j],float(textl[j])) for j in range(len(textval)) if((len(textl[j])!=0) and (len(textval[j])!=0))]) X=np.array([[0. for i in range(Number_of_columns)] for j in range(Number_of_rows)]) i=0 for line in f: line0=line.strip() line1=line0.split() passing=1 for dicts, vals in labele.items(): if dicts in labelel: if(labelel[dicts]>float(line1[vals])): passing=0 if dicts in labeleu: if(labeleu[dicts]<float(line1[vals])): passing=0 if(passing==1): for j in range(Number_of_columns): X[i][j]=float(line1[j]) i=i+1 X=X[0:i,:] X=np.array([[X[k][l] for l in range(Number_of_columns)] for k in range(i) ]) fig=plt.figure(figsize=(20,15)) count=1 for ime, val in labele.items(): ax=fig.add_subplot(2,3,count) ax.set_xlabel(ime, size=30) ax.hist(X[:,val], bins=50, normed=False, histtype='stepfilled',color='blue',facecolor='blue') ax.axvline(np.mean(X[:,val]), color='orange', linestyle='--') ax.axvline(np.median(X[:,val]), color='green', linestyle='--') ax.xaxis.major.formatter._useMathText = True ax.ticklabel_format(style='sci', axis='x', scilimits=(-5,5)) text='Mean and median:\n'+str("mean$\\rightarrow$ $ {:.2uL}$\n".format(ufloat(np.mean(X[:,val]),np.std(X[:,val])))+"median$\\rightarrow$ $ {:.2uL}$".format(ufloat(np.median(X[:,val]),sigmaG(X[:,val]) ) )) finishing_string=finishing_string+ime+" & "+"$ {:.2uL}$".format(ufloat(np.mean(X[:,val]),np.std(X[:,val])))+" & $ {:.2uL}$".format(ufloat(np.median(X[:,val]),sigmaG(X[:,val])))+"\\\\ \n" finishing_list.append([ime,"$ {:.2uL}$".format(ufloat(np.mean(X[:,val]),np.std(X[:,val])))," $ {:.2uL}$".format(ufloat(np.median(X[:,val]),sigmaG(X[:,val])))]) ax.text(.65,.9,text,transform = ax.transAxes) count=count+1 plt.tight_layout() plt.savefig(direktorij+'/Histogrami.png') plt.close() reportwin(starting_list,finishing_string,finishing_list) for names0,vals0 in labele.items(): fig=plt.figure(figsize=(30,25)) labele1=deepcopy(labele) del labele1[names0] labele2=deepcopy(labele1) nx=ceil(np.sqrt(len(labele1)*(len(labele1)-1)/2)) ny=ceil(len(labele1)*(len(labele1)-1)/2/nx) #fig, axes = plt.subplots(nrows=2, ncols=2, sharex=True, sharey=True) counts=1 cmap_multicolor = plt.cm.jet for names,vals in labele1.items(): del labele2[names] for names1, vals1 in labele2.items(): N0, xedges0, yedges0 = binned_statistic_2d(X[:,vals], X[:,vals1], X[:,labele[names0]], 'mean', bins=100) ax=fig.add_subplot(ny,nx,counts) im=ax.imshow(N0.T, origin='lower',extent=[xedges0[0], xedges0[-1], yedges0[0], yedges0[-1]], aspect='auto', interpolation='nearest', cmap=cmap_multicolor) plt.xlim(xedges0[0], xedges0[-1]) plt.ylim(yedges0[0], yedges0[-1]) plt.xlabel(names, size=30) plt.ylabel(names1, size=30) ax.xaxis.major.formatter._useMathText = True ax.yaxis.major.formatter._useMathText = True ax.ticklabel_format(style='sci', axis='x', scilimits=(-5,5)) #m_1 = np.linspace(xedges0[0], xedges0[-1], 100) #m_2 = np.linspace(yedges0[0], yedges0[-1], 100) #MX,MY = np.meshgrid(m_1, m_2) #Z = sigmas(MX,np.median(X[:,vals]),sigmaG(X[:,vals]), MY,np.median(X[:,vals1]),sigmaG(X[:,vals1])) H, xbins, ybins = np.histogram2d(X[:,vals], X[:,vals1],bins=100) Nsigma = convert_to_stdev(np.log(H)) cont=plt.contour(0.5 * (xbins[1:] + xbins[:-1]),0.5 * (ybins[1:] + ybins[:-1]),Nsigma.T,levels=[0.6827,0.6827,0.9545, 0.9545], colors=['.25','.25','0.5','0.5'],linewidths=2) counts=counts+1 cmap_multicolor.set_bad('w', 1.) fig.subplots_adjust(bottom=0.1) cbar_ax = fig.add_axes([0.1, 0.05, 0.8, 0.025]) cb=fig.colorbar(im, cax=cbar_ax, format=r'$%.1f$',orientation='horizontal') cb.set_label(str('$\\langle '+names0.replace('$','')+'\\rangle $'), size=30) plt.savefig(direktorij+'/'+''.join([i for i in names0 if (i.isalpha() or i.isdigit())])+'.png',bbox_inches='tight') plt.close()
def plot_sample_distribution( x_arr, y_arr, z_arr, method='count', x_bins=25, y_bins=25, z_min=None, z_max=None, contour=True, nticks=5, x_lim=[8.5, 12], y_lim=[-3.3, 1.5], n_contour=6, scatter=True, colorbar=False, gaussian=1, xlabel=r'$\log (M_{*}/M_{\odot})$', ylabel=r'$\log (\rm{SFR}/M_{\odot}\rm{yr}^{-1})$', title=None, x_title=0.6, y_title=0.1, s_alpha=0.1, s_size=10): """Density plot.""" from astroML.stats import binned_statistic_2d from scipy.ndimage.filters import gaussian_filter ORG = plt.get_cmap('OrRd') ORG_2 = plt.get_cmap('YlOrRd') BLU = plt.get_cmap('PuBu') BLK = plt.get_cmap('Greys') PUR = plt.get_cmap('Purples') GRN = plt.get_cmap('Greens') plt.rcParams['figure.dpi'] = 100.0 plt.rc('text', usetex=True) if x_lim is None: x_lim = [np.nanmin(x_arr), np.nanmax(x_arr)] if y_lim is None: y_lim = [np.nanmin(y_arr), np.nanmax(y_arr)] x_mask = ((x_arr >= x_lim[0]) & (x_arr <= x_lim[1])) y_mask = ((y_arr >= y_lim[0]) & (y_arr <= y_lim[1])) x_arr = x_arr[x_mask & y_mask] y_arr = y_arr[x_mask & y_mask] z_arr = z_arr[x_mask & y_mask] z_stats, x_edges, y_edges = binned_statistic_2d( x_arr, y_arr, z_arr, method, bins=(np.linspace(8, 12, x_bins), np.linspace(-3.0, 1.5, y_bins))) if z_min is None: z_min = np.nanmin(z_stats) if z_max is None: z_max = np.nanmax(z_stats) fig = plt.figure(figsize=(9, 6)) fig.subplots_adjust(left=0.14, right=0.93, bottom=0.12, top=0.99, wspace=0.00, hspace=0.00) ax1 = fig.add_subplot(111) #ax1.grid(linestyle='--', linewidth=2, alpha=0.5, zorder=0) if contour: CT = ax1.contour(x_edges[:-1], y_edges[:-1], gaussian_filter(z_stats.T, gaussian), n_contour, linewidths=1.5, colors=[BLK(0.6), BLK(0.7)], extend='neither') #ax1.clabel(CT, inline=1, fontsize=15) z_stats[z_stats==0] = np.nan HM = ax1.imshow(z_stats.T, origin='lower', extent=[x_edges[0], x_edges[-1], y_edges[0], y_edges[-1]], vmin=z_min, vmax=z_max, aspect='auto', interpolation='none', cmap=BLK) if scatter: sc = ax1.scatter(x_arr, y_arr, c=z_arr, cmap='Spectral', alpha=0.3, s=s_size, label='__no_label__', zorder=1) ax1.colorbar(sc, ax=ax1, orientation='horizontal') ax1.set_xlabel(xlabel, size=25) ax1.set_ylabel(ylabel, size=25) ax1.set_yticks([-3, -2, -1, 0, 1]) for tick in ax1.xaxis.get_major_ticks(): tick.label.set_fontsize(22) for tick in ax1.yaxis.get_major_ticks(): tick.label.set_fontsize(22) if colorbar: from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable from matplotlib.ticker import MaxNLocator divider = make_axes_locatable(ax1) cax = divider.append_axes("right", size="5%", pad=0.2) cbar_ticks = MaxNLocator(nticks).tick_values(z_min, z_max) cbar = plt.colorbar(HM, cax=cax, ticks=cbar_ticks) cbar.solids.set_edgecolor("face") if title is not None: ax1.text(x_title, y_title, title, size=30, transform=ax1.transAxes) ax1.set_xlim(x_lim) ax1.set_ylim(y_lim) ax1.tick_params(direction='in') return fig, z_stats, x_edges, y_edges
plt.rc('xtick', direction='inout') plt.rc('ytick', direction='inout') plt.rc('axes', linewidth=1.5) plt.rc('font', family='sans-serif') plt.rc('font', size=18) # In[117]: D = np.loadtxt('../catalogs/Imag_MB.dat') Imag = D[:, 0] MB = D[:, 1] zB = D[:, 2] # In[118]: z_mean, xe, ye = binned_statistic_2d(Imag, MB, zB, 'mean', bins=50) N, xedges, yedges = binned_statistic_2d(Imag, MB, zB, 'count', bins=50) # In[48]: fig = plt.figure(figsize=(15, 8)) fig.subplots_adjust(wspace=0.25, left=0.1, right=0.95, bottom=0.07, top=0.95) #-------------------- # First axes: plt.subplot(121) plt.imshow(np.log10(N.T), origin='lower', extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]], aspect='auto', interpolation='nearest',
def plot_cont_galaxy(filename, N_bulge, N_disk, bin_no=100): #If you have enough particle resolution, choose 1000 tmp = filename.split('.npy') t = tmp[0].split('galaxy_')[1] galaxy = np.load('%s'%(filename)) x_gal = np.zeros_like(galaxy[0]) y_gal = np.zeros_like(galaxy[1]) z_gal = np.zeros_like(galaxy[2]) cs_gal = galaxy[5] cont = galaxy[4]/np.sum(galaxy[4]) # Bulge (Spherical to Cartesian) r_gal = galaxy[0,:N_bulge] theta_gal = galaxy[1,:N_bulge] phi_gal_sph = galaxy[2,:N_bulge] x_gal[:N_bulge] = r_gal*np.sin(theta_gal)*np.cos(phi_gal_sph) y_gal[:N_bulge] = r_gal*np.sin(theta_gal)*np.sin(phi_gal_sph) z_gal[:N_bulge] = r_gal*np.cos(theta_gal) # Disk (Cylindrical to Cartesian) rho_gal = galaxy[0,N_bulge:N_bulge+N_disk] phi_gal_cyl = galaxy[1,N_bulge:N_bulge+N_disk] z_gal_cyl = galaxy[2,N_bulge:N_bulge+N_disk] x_gal[N_bulge:N_bulge+N_disk] = rho_gal*np.cos(phi_gal_cyl) y_gal[N_bulge:N_bulge+N_disk] = rho_gal*np.sin(phi_gal_cyl) z_gal[N_bulge:N_bulge+N_disk] = z_gal_cyl # Halo (Spherical to Cartesian) r_gal = galaxy[0,N_bulge+N_disk:] theta_gal = galaxy[1,N_bulge+N_disk:] phi_gal_sph = galaxy[2,N_bulge+N_disk:] x_gal[N_bulge+N_disk:] = r_gal*np.sin(theta_gal)*np.cos(phi_gal_sph) y_gal[N_bulge+N_disk:] = r_gal*np.sin(theta_gal)*np.sin(phi_gal_sph) z_gal[N_bulge+N_disk:] = r_gal*np.cos(theta_gal) # Spot the colonizer inds = np.where(cs_gal!=0)[0] x_col = x_gal[inds] y_col = y_gal[inds] z_col = z_gal[inds] colonized_fraction = abs(np.sum(cs_gal)/len(cs_gal)) from astroML.plotting import setup_text_plots setup_text_plots(fontsize=16, usetex=False) from astroML.stats import binned_statistic_2d fig = plt.figure(figsize=(20, 10)) # Face-on axfo = plt.subplot(121) cmap = plt.cm.spectral_r cmap.set_bad('w', 0.) N, xedges, yedges = binned_statistic_2d(x_gal*1e-3, y_gal*1e-3, cont, 'sum', bins=bin_no) plt.imshow((N.T), origin='lower', extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]], aspect='equal', interpolation='nearest', cmap=cmap) plt.xlabel(r'X (kpc)') plt.ylabel(r'Y (kpc)') plt.xlim([-1e1, 1e1]) plt.ylim([-1e1, 1e1]) cb = plt.colorbar(pad=0.2, orientation='horizontal') cb.set_label(r'$\mathrm{log(L/L_{total})}$') clim_min = min(cont) clim_max = max(cont) plt.title("time = %s Myr"%(t)) # plt.clim(clim_min, clim_max) # Edge-on axeo = plt.subplot(122) cmap = plt.cm.spectral_r cmap.set_bad('w', 0.) N, xedges, zedges=binned_statistic_2d(x_gal*1e-3, z_gal*1e-3, cont, 'sum', bins=bin_no) plt.imshow((N.T), origin='lower', extent=[xedges[0], xedges[-1], zedges[0], zedges[-1]], aspect='equal', interpolation='nearest', cmap=cmap) plt.xlabel(r'X (kpc)') plt.ylabel(r'Z (kpc)') plt.xlim([-1e1, 1e1]) plt.ylim([-1e1, 1e1]) cb = plt.colorbar(pad=0.2, orientation='horizontal') cb.set_label(r'$\mathrm{log(L/L_{total})}$') clim_min = min(cont) clim_max = max(cont) # print ("Colonized fraction = %.2f"%(colonized_fraction)) # plt.clim(clim_min, clim_max) # plt.title("Colonized fraction = %.2f"%(abs(colonized_fraction))) plt.savefig("%s.svg"%(filename)) plt.savefig("%s.png"%(filename)) # plt.show() return galaxy
def plotPanel(axes, xVec, yVec, zVec, CCstat="", CCtype="", xMin="", xMax="", yMin="", yMax="", xLabel="", yLabel="", title=""): ## axes, etc. # axes limits if (xMin == ""): xMin = np.min(xVec) if (xMax == ""): xMax = np.max(xVec) axes.set_xlim(xMin, xMax) if (yMin == ""): yMin = np.min(yVec) if (yMax == ""): yMax = np.max(yVec) axes.set_ylim(yMin, yMax) # axes labels if (xLabel == ""): xLabel = "X" if (yLabel == ""): yLabel = "Y" axes.set_xlabel(xLabel, fontsize=14) axes.set_ylabel(yLabel, fontsize=14) # title axes.set_title(title) # make bigger ticmark labels for tick in axes.xaxis.get_major_ticks(): tick.label.set_fontsize(12) for tick in axes.yaxis.get_major_ticks(): tick.label.set_fontsize(12) ## bin N, xedges, yedges = binned_statistic_2d(xVec, yVec, zVec, 'count', bins=100) if (CCstat == ""): Zmean, xedges, yedges = binned_statistic_2d(xVec, yVec, zVec, 'mean', bins=100) else: Zmean, xedges, yedges = binned_statistic_2d(xVec, yVec, zVec, funcStdDev, bins=100) ## plot cmap_multicolor = plt.cm.jet cmap_multicolor.set_bad('w', 1.) plt.imshow(Zmean.T, origin='lower', extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]], aspect='auto', interpolation='nearest', cmap=cmap_multicolor) # special cases if (CCtype == "FeH"): cb = plt.colorbar(ticks=np.arange(-2.5, 1, 1), pad=0.16, format=r'$%.1f$', orientation='horizontal') cb.set_label(r'$\mathrm{mean\ [Fe/H]\ in\ pixel}$', fontsize=12) plt.clim(-2.5, 0.5) if (CCtype == "logg"): cb = plt.colorbar(ticks=np.arange(0, 4, 1), pad=0.16, format=r'$%.1f$', orientation='horizontal') cb.set_label(r'$\mathrm{mean\ log(g)\ in\ pixel}$', fontsize=12) plt.clim(0, 4) if (CCtype == "vRad"): cb = plt.colorbar(ticks=np.arange(0, 150, 25), pad=0.16, format=r'$%.1f$', orientation='horizontal') cb.set_label(r'$\mathrm{\ vel. disp. (km/s) \ in\ pixel}$', fontsize=12) plt.clim(0, 150) # density contours over the colors levels = np.linspace(0, np.log10(N.max()), 7)[2:] plt.contour(np.log10(N.T), levels, colors='k', extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]])
from astroML.datasets import fetch_sdss_sspp data = fetch_sdss_sspp() # do some reasonable magnitude cuts rpsf = data['rpsf'] data = data[(rpsf > 15) & (rpsf < 19)] # get the desired data logg = data['logg'] Teff = data['Teff'] FeH = data['FeH'] #------------------------------------------------------------ # Plot the results using the binned_statistic function from astroML.stats import binned_statistic_2d N, xedges, yedges = binned_statistic_2d(Teff, logg, FeH, 'count', bins=100) FeH_mean, xedges, yedges = binned_statistic_2d(Teff, logg, FeH, 'mean', bins=100) # Define custom colormaps: Set pixels with no sources to white cmap = plt.cm.copper cmap.set_bad('w', 1.) cmap_multicolor = plt.cm.jet cmap_multicolor.set_bad('w', 1.) # Create figure and subplots fig = plt.figure(figsize=(5, 2)) fig.subplots_adjust(wspace=0.22, left=0.1, right=0.95, bottom=0.12, top=0.95)
def pdf_plot(self, xcol, ycol, zcol, stat='median', bins='uniq', log=False, cbar=True, inds=None, ax=None, vmin=None, vmax=None): try: from astroML.stats import binned_statistic_2d except ImportError: print('need astroML.stats.binned_statistic_2d for this function') return -1 if inds is None: inds = np.arange(len(self.data[xcol])) if bins == 'uniq': bins = [ np.unique(self.data[xcol][inds]), np.unique(self.data[ycol][inds]) ] N, xe, ye = binned_statistic_2d(self.data[xcol][inds], self.data[ycol][inds], self.data[zcol][inds], stat, bins=bins) if log is True: n = np.log10(N.T) else: n = N.T aspect = (xe[-1] - xe[0]) / (ye[-1] - ye[0]) if ax is None: fig, ax = plt.subplots() im = ax.imshow(n, extent=[xe[0], xe[-1], ye[0], ye[-1]], vmin=vmin, vmax=vmax, cmap=plt.cm.Blues_r, aspect=aspect, interpolation='nearest') ax.set_xlabel(key2label(xcol), fontsize=16) ax.set_ylabel(key2label(ycol), fontsize=16) if cbar: cb = plt.colorbar(im) if callable(stat): stat = stat.__name__ cb.set_label(r'$\rm{%s}$\ %s' % (stat, key2label(zcol))) ax = (ax, cb) return ax
from astroML.datasets import fetch_sdss_sspp data = fetch_sdss_sspp() # do some reasonable magnitude cuts rpsf = data['rpsf'] data = data[(rpsf > 15) & (rpsf < 19)] # get the desired data logg = data['logg'] Teff = data['Teff'] FeH = data['FeH'] #------------------------------------------------------------ # Plot the results using the binned_statistic function from astroML.stats import binned_statistic_2d N, xedges, yedges = binned_statistic_2d(Teff, logg, FeH, 'count', bins=100) FeH_mean, xedges, yedges = binned_statistic_2d(Teff, logg, FeH, 'mean', bins=100) # Define custom colormaps: Set pixels with no sources to white cmap = plt.cm.copper cmap.set_bad('w', 1.) cmap_multicolor = plt.cm.jet cmap_multicolor.set_bad('w', 1.) # Create figure and subplots fig = plt.figure(figsize=(10, 4))
figsize=(8 * nf, 8.), sharex=True, sharey=True, gridspec_kw={ 'width_ratios': [1] * nc, 'height_ratios': [1] * nf }) for r in range(nf): for c in range(nc): zi = zbins[nc * r + c] zf = zbins[nc * r + (c + 1)] xx = I[nc * r + c] yy = B[nc * r + c] N, xedges, yedges = binned_statistic_2d(xx, yy, xx, 'count', bins=50, range=[(-26, -15), (-26, -15)]) xb = xedges[:-1] + np.diff(xedges)[0] / 2. yb = yedges[:-1] + np.diff(yedges)[0] / 2. ax[r, c].contourf(xb, yb, np.log10(N.T), cmap='PuBu_r', origin='lower', extent=[ yedges[0], yedges[-1], xedges[0], xedges[-1], ],