def plot_cnt_graph( xvs, # x values cnt1y, # y values, cnt2y, title=None, label=None, save_name=None, y_label=None, x_label=None): plt.figure(figsize=(15, 6)) p1 = plt.bar(xvs, cnt1y, 0.35, label="1") p2 = plt.bar(xvs, cnt2y, 0.35, bottom=cnt1y, label="2") if title: plt.title(title) # 'io-static {} performance'.format(label)) if y_label: plt.ylabel(y_label) if x_label: plt.xlabel(x_label) plt.set_xscale('log') plt.set_xticks(xvs) plt.set_xticklabels([i / 1024 for i in xvs], rotation=0) plt.grid('on', axis='x') plt.grid('on', axis='y') plt.legend() if save_name: plt.savefig(save_name) return ax
def plotXPosterior(X, L, Z, space): """ Plots X*L(X)/Z in log X space, not including KDE methods Args: x : array inputs to likelihood function L : array likelihood values Z : float Bayesian evidence space : string whether to calculate likelihood or log of it """ if space == 'log': LhoodDivZ = np.exp(L - Z) X = np.exp(X) else: LhoodDivZ = L / Z LXovrZ = X * LhoodDivZ plt.figure('posterior') plt.scatter(X, LXovrZ) plt.set_xscale('log') plt.show() plt.close()
def plot_many_curves(data, parameters=None, fname=None): """ Plot many curve on the given axis with the given parameters """ params = process_parameters(parameters) plt.rc('font', **params['font']) fig = plt.figure(num=None, figsize=params['size'], dpi=params['dpi']) fig.clf() axis = plt.subplot(111) for d in data: plt.plot(d[0], d[1], lw=1, label=d[2]) plt.grid(axis='y', color="0.9", linestyle='-', linewidth=1) axis.spines['top'].set_visible(False) axis.spines['right'].set_visible(False) axis.spines['left'].set_visible(False) axis.get_xaxis().tick_bottom() axis.get_yaxis().tick_left() axis.tick_params(axis='x', direction='out') axis.tick_params(axis='y', length=0) for spine in axis.spines.values(): spine.set_position(('outward', 5)) axis.set_axisbelow(True) axis.set_xlabel(params['xlabel']) axis.set_ylabel(params['ylabel']) if params['logscale'] == 'y': plt.set_yscale('log') if params['logscale'] == 'x': plt.set_xscale('log') plt.legend(loc='upper right', frameon=False) # draw & show / save image if fname is None: plt.draw() plt.show() else: plt.savefig(fname)
def density_profile(sim, linestyle=False, center=True, clear=True, fit=False,in_units=None, filename=None, fit_factor=0.02, axes=False, **kwargs): ''' 3d density profile **Options:** *filename* (None): name of file to which to save output **Usage:** >>> import pynbody.plot as pp >>> h = s.halos() >>> pp.density_profile(h[1],linestyle='dashed',color='k') ''' if axes: plt = axes else: import matplotlib.pyplot as plt global config logger.info("Centering...") if center: halo.center(sim, mode='ssc') logger.info("Creating profile...") if 'min' in kwargs: ps = profile.Profile( sim, ndim=3, type='log', nbins=40, min=kwargs['min']) del kwargs['min'] else: ps = profile.Profile(sim, ndim=3, type='log', nbins=40) if clear and not axes: plt.clf() critden = (units.Unit('100 km s^-1 Mpc^-1') * sim.properties['h']) ** 2 / 8.0 / np.pi / units.G r = ps['rbins'].in_units('kpc') if in_units is None: den = ps['density'].in_units(critden) else: den = ps['density'].in_units(in_units) if linestyle: plt.errorbar(r, den, yerr=den / np.sqrt(ps['n']), linestyle=linestyle, **kwargs) else: plt.errorbar(r, den, yerr=den / np.sqrt(ps['n']), fmt='o', **kwargs) if in_units is None: ylabel=r'$\rho / \rho_{cr}$' # +den.units.latex()+'$]') else: ylabel=r'$\rho / '+den.units.latex()+'$' if axes: plt.set_yscale('log') plt.set_xscale('log') plt.set_xlabel('r [kpc]') plt.set_ylabel(ylabel) #r'$\rho / \rho_{cr}$') # +den.units.latex()+'$]') else: plt.yscale('log') plt.xscale('log') plt.xlabel('r [kpc]') plt.ylabel(ylabel) #r'$\rho / \rho_{cr}$') # +den.units.latex()+'$]') if (filename): logger.info("Saving %s", filename) plt.savefig(filename) if fit: fit_inds = np.where(r < fit_factor*sim['r'].max()) alphfit = np.polyfit(np.log10(r[fit_inds]), np.log10(den[fit_inds]), 1) # print "alpha: ", alphfit[0], " norm:", alphfit[1] fit = np.poly1d(alphfit) plt.plot(r[fit_inds], 10**fit(np.log10(r[fit_inds])), color='k',linestyle='dashed', label=r'$\alpha$=%.1f'%alphfit[0]) plt.legend(loc=3) return alphfit[0]
def plot_shaded_plot(x, y, parameters=None, fname=None): """ Plot boxplot for set of data (median and shaded quartiles) where data is a list of lists of values data = [ [...] , ... , [...] ] """ params = process_parameters(parameters) plt.rc('font', **params['font']) perc_05, perc_25, med, perc_75, perc_95 = percentiles(y) fig = plt.figure(num=None, figsize=params['size'], dpi=params['dpi']) axis = plt.subplot(111) plt.clf() if params['quartiles']: plt.fill_between(x, perc_25, perc_75, alpha=0.5, linewidth=0.1, color=params['quart-color']) plt.fill_between(x, perc_75, perc_95, alpha=0.25, linewidth=0.1, color=params['quart-color']) plt.fill_between(x, perc_05, perc_25, alpha=0.25, linewidth=0.1, color=params['quart-color']) plt.plot(x, med, lw=1, alpha=1.0, label=params['label'], color=params['quart-color']) plt.grid(axis='y', color="0.9", linestyle='-', linewidth=1) axis.spines['top'].set_visible(False) axis.spines['right'].set_visible(False) axis.spines['left'].set_visible(False) axis.get_xaxis().tick_bottom() axis.get_yaxis().tick_left() axis.tick_params(axis='x', direction='out') axis.tick_params(axis='y', length=0) for spine in axis.spines.values(): spine.set_position(('outward', 5)) axis.set_axisbelow(True) axis.set_xlabel(params['xlabel']) axis.set_ylabel(params['ylabel']) if params['logscale'] == 'y': plt.set_yscale('log') if params['logscale'] == 'x': plt.set_xscale('log') # draw & show / save image if fname is None: plt.draw() plt.show() else: plt.savefig(fname)
for h in histograms: fig += 1 if plotallhistos or h.title.find(opts.SINGLETITLE)>-1: centers = [] widths = [] sumw = [] sumw2 = [] for bin in h: centers.append(bin.midpoint) widths.append(bin.width) sumw.append(bin.sumW) sumw2.append(bin.sumW2) yerr = map(lambda x: math.sqrt(x), sumw2) if opts.LOGY: plt.set_yscale("log") if opts.LOGX: plt.set_xscale("log") thislegend = Legend(h.title,h.title,"green") if opts.LEGEND!="": leg = readLegend(opts.LEGEND) for l in leg: if l.title==h.title: thislegend=l #ax.errorbar(centers, sumw, yerr=yerr, xerr=widths, fmt='o') plt.figure(fig) plt.hist(centers,bins=len(centers),weights=sumw,normed=opts.NORM,facecolor=thislegend.color,alpha=0.5) plt.title(thislegend.nicename) plt.show()
def metal_vs_age_subplot(plt,fits,metal,bv =.65,pdfPage=None,showPlots=False,title=None,\ shadeScatter=False,errorbars=True,bv_m=None,upper_lim=None, \ mamajek_poly=False,metal_val=None,logAge = True,plotStars=False,omit_cluster=None,legend=True): const = init_constants(metal) rhk, scatter, CLUSTER_AGES, CLUSTER_NAMES = my_fits.get_valid_metal( bv, fits, const, None, None, omit_cluster) #plt.figure(figsize=(7,5)) if metal_val: plt.hlines(metal_val,0,const.GALAXY_AGE,linestyle='dashed',color='orange',\ label=metal[:2].title() + ' = %.2f' % metal_val) MARKERS, COLORS = const.MARKERS, const.COLORS if metal == 'lithium': if bv >= const.BLDB_LOWER_LIM: colors = [ const.COLORS[const.CLUSTER_NAMES.index(name)] for name in CLUSTER_NAMES[1:-1] ] markers = [ const.MARKERS[const.CLUSTER_NAMES.index(name)] for name in CLUSTER_NAMES[1:-1] ] MARKERS = [const.PRIM_MARKER] + markers + [const.BLDB_MARKER] COLORS = [const.PRIM_COLOR] + colors + [const.BLDB_COLOR] else: colors = [ const.COLORS[const.CLUSTER_NAMES.index(name)] for name in CLUSTER_NAMES[1:] ] markers = [ const.MARKERS[const.CLUSTER_NAMES.index(name)] for name in CLUSTER_NAMES[1:] ] MARKERS = [const.PRIM_MARKER] + markers COLORS = [const.PRIM_COLOR] + colors for i in range(len(rhk)): if (errorbars): plt.errorbar(CLUSTER_AGES[i], rhk[i], yerr=scatter[i],color=COLORS[i],\ marker=MARKERS[i],markersize=8,capsize=4,zorder=10) plt.scatter([], [], color=COLORS[i], marker=MARKERS[i], label=CLUSTER_NAMES[i]) else: plt.scatter(CLUSTER_AGES[i], rhk[i],color=COLORS[i],marker=MARKERS[i],\ label=CLUSTER_NAMES[i],s=80,zorder=10) mu, sig, lbl = my_fits.vs_age_fits(bv, CLUSTER_AGES, rhk, scatter, metal, omit_cluster) plt.plot(const.AGE, mu(const.AGE), label=lbl) if (plotStars and bv_m is not None): bv_threshold = 0.05 if metal == 'lithium' else 1 for c in range(len(bv_m)): bv_arr = np.array(bv_m[c][0]) mask = (bv_arr >= bv - bv_threshold) & (bv_arr <= bv + bv_threshold) li = np.array(bv_m[c][1])[mask] star_ages = [const.CLUSTER_AGES[c]] * len(li) ul = np.array( upper_lim[c])[mask] if upper_lim is not None else None for j in range(len(li)): m = const.DOWN_ARROW if (upper_lim is not None and ul[j]) else '+' color = const.COLORS[ c] # if metal == 'lithium' else const.COLORS[c] plt.scatter(const.CLUSTER_AGES[c], li[j], marker=m, s=30, color=color) #for primordial li if (shadeScatter): plt.fill_between(const.AGE, mu(const.AGE) - sig(const.AGE), mu(const.AGE) + sig(const.AGE), alpha=.2, color='C0') if (mamajek_poly and metal[0].lower() == 'c'): plt.plot(const.AGE,utils.getMamaRHK(const.AGE),linestyle='--',color='gray',\ label='M & H 2008') #ax = plt.gca() if logAge: plt.set_xscale('log') plt.axis([1, const.GALAXY_AGE] + const.METAL_RANGE) if legend: plt.legend() #plt.set_xlabel('Age (Myr)',size=AXIS_LABEL_SIZE) #ylabel = set_ylabel(metal) if (title): plt.set_title(title, size=TITLE_SIZE) #plt.tight_layout() plt.minorticks_on() plt.tick_params(axis='both', which='both', right=True, top=True)