def _preplot(directory, file_, X, Y, dX, dY, title_="", fig="^^", Xscale="linear", Yscale="linear", Xlab="", Ylab=""): # print a raw plot of the data, see fast_plot for the public function figure(fig + "_2") if (fig == file_): clf() title(title_) xlabel(Xlab) ylabel(Ylab) if Xscale == "log": xscale("log") if Yscale == "log": yscale("log") grid(b=True) errorbar(X, Y, dY, dX, fmt=",", ecolor="black", capsize=0.5) savefig(directory + "grafici/fast_plot_" + fig + ".pdf") savefig(directory + "grafici/fast_plot_" + fig + ".png")
def plot(self): f = pylab.figure(figsize=(8,4)) co = [] #colors container for zScore, r in itertools.izip(self.zScores, self.log2Ratio): if zScore < self.pCut: if r > 0: co.append(Colors().greenColor) elif r < 0: co.append(Colors().redColor) else: raise Exception else: co.append(Colors().blueColor) #print "Probability this is from a normal distribution: %.3e" %stats.normaltest(self.log2Ratio)[1] ax = f.add_subplot(121) pylab.axvline(self.meanLog2Ratio, color=Colors().redColor) pylab.axvspan(self.meanLog2Ratio-(2*self.stdLog2Ratio), self.meanLog2Ratio+(2*self.stdLog2Ratio), color=Colors().blueColor, alpha=0.2) his = pylab.hist(self.log2Ratio, bins=50, color=Colors().blueColor) pylab.xlabel("log2 Ratio %s/%s" %(self.sampleNames[1], self.sampleNames[0])) pylab.ylabel("Frequency") ax = f.add_subplot(122, aspect='equal') pylab.scatter(self.genes1, self.genes2, c=co, alpha=0.5) pylab.ylabel("%s RPKM" %self.sampleNames[1]) pylab.xlabel("%s RPKM" %self.sampleNames[0]) pylab.yscale('log') pylab.xscale('log') pylab.tight_layout()
def plot_pp(var): jobs_orig.sort(key=lambda job: getattr(job, var)) pylab.subplot(211) for ch in (10, 50, 200): xs = [getattr(job, var) for job in jobs_orig if job.ch_objects == ch] if xs: pylab.plot(xs, [(job.ef11[-1] + job.ef10[-1]) / job.ef11[0] for job in jobs_orig if job.ch_objects==ch], 'o-', label=r'$ch=%.0f$'%ch) pylab.xscale('log') pylab.xlabel(r'$%s$'%(var,)) pylab.ylabel(r'$(ef_{11}^n+ef_{10}^n)/ef_{11}^0$') pylab.legend(loc='best') pylab.subplot(212) for ch in (10, 50, 200): xs = [getattr(job, var) for job in jobs_orig if job.ch_objects == ch] if xs: pylab.plot(xs, [job.hf_eq11 / job.ef11[-1] for job in jobs_orig if job.ch_objects==ch], 'o-', label=r'$ch=%.0f$'%ch) pylab.xscale('log') pylab.xlabel(r'$%s$'%(var,)) pylab.ylabel(r'$hf{11}^n(Q=0) / ef_{11}^n$') pylab.legend(loc='best') pylab.savefig(var+'.png')
def Validation(): numSamples = 1000000 theta = np.random.rand(numSamples)*np.pi ECo60 = np.array([1.117,1.332]) Ef0,Ee0 = Compton(ECo60[0],theta) Ef1,Ee1 = Compton(ECo60[1],theta) dSdE0 = diffXSElectrons(ECo60[0],theta) dSdE1 = diffXSElectrons(ECo60[1],theta) # Sampling Values values = list() piMax = np.max([dSdE0,dSdE1]) while (len(values) < numSamples): values.append(SampleRejection(piMax,ComptonScattering)) # Binning the data bins = np.logspace(-3,0.2,100) counts = np.histogram(values,bins) counts = counts[0]/float(len(values)) binCenters = 0.5*(bins[1:]+bins[:-1]) # Plotting pylab.figure() pylab.plot(binCenters,counts,ls='steps') #pylab.bar(binCenters,counts,align='center') pylab.grid(True) pylab.xlim((1E-3,1.4)) pylab.xlabel('Electron Energy (MeV)') pylab.ylabel('Frequency per Photon') pylab.yscale('log') pylab.xscale('log') pylab.savefig('ValComptonScatteringXS.png')
def plot_numedition_size(_itemFreqList, labels, colors, path, xlabel, ylabel, xlog, ylog): fig = plt.figure(figsize=(6, 6)) if len(colors) == 0: plt.gca().set_color_cycle(['pink', 'blue', 'yellow', 'red', 'black']) else: plt.gca().set_color_cycle(colors) numberOfFrequency_sorted = {} for _itemFreq in _itemFreqList: _itemFreq_sorted = np.array(sorted(_itemFreq, key=lambda x: x[0])) numberOfFrequency_sorted = _itemFreq_sorted[:, 1] numberOfReviews_sorted = _itemFreq_sorted[:, 0] plt.plot(numberOfReviews_sorted, numberOfFrequency_sorted, linewidth=1) #plt.title("ccdf plot") if xlog == 1: plt.xscale('log') plt.xlabel('$log \/ ' + xlabel + ' $') else: plt.xlabel(xlabel) if ylog == 1: plt.yscale('log') plt.ylabel("$ log " + ylabel) else: plt.ylabel(ylabel) plt.legend(labels, loc='upper right') plt.grid(False) plt.savefig(path, bbox_inches='tight') plt.close()
def compare(self, x, precision, target, linear=False, diff="relative"): r""" Compare the different computation methods using the given precision. """ if precision == 'single': #n=11; plotdiff(x, target, self.call_mpmath(x, n), 'mp %d bits'%n, diff=diff) #n=23; plotdiff(x, target, self.call_mpmath(x, n), 'mp %d bits'%n, diff=diff) pass elif precision == 'double': #n=53; plotdiff(x, target, self.call_mpmath(x, n), 'mp %d bits'%n, diff=diff) #n=83; plotdiff(x, target, self.call_mpmath(x, n), 'mp %d bits'%n, diff=diff) pass plotdiff(x, target, self.call_numpy(x, precision), 'numpy ' + precision, diff=diff) plotdiff(x, target, self.call_ocl(x, precision, 0), 'OpenCL ' + precision, diff=diff) pylab.xlabel(self.xaxis) if diff == "relative": pylab.ylabel("relative error") elif diff == "absolute": pylab.ylabel("absolute error") else: pylab.ylabel(self.name) pylab.semilogx(x, target, '-', label="true value") if linear: pylab.xscale('linear')
def solid_plot(): # reference values, see sref = 0.0924102 wref = 0.000170152 # List of the element types to process (text files) eltyps = ["C3D8", "C3D8R", "C3D8I", "C3D20", "C3D20R", "C3D4", "C3D10"] pylab.figure(figsize=(10, 5.0), dpi=100) pylab.subplot(1, 2, 1) pylab.title("Stress") # pylab.hold(True) # deprecated for elty in eltyps: data = numpy.genfromtxt(elty + ".txt") pylab.plot(data[:, 1], data[:, 2] / sref, "o-") pylab.xscale("log") pylab.xlabel('Number of nodes') pylab.ylabel('Max $\sigma / \sigma_{\mathrm{ref}}$') pylab.grid(True) pylab.subplot(1, 2, 2) pylab.title("Displacement") # pylab.hold(True) # deprecated for elty in eltyps: data = numpy.genfromtxt(elty + ".txt") pylab.plot(data[:, 1], data[:, 3] / wref, "o-") pylab.xscale("log") pylab.xlabel('Number of nodes') pylab.ylabel('Max $u / u_{\mathrm{ref}}$') pylab.ylim([0, 1.2]) pylab.grid(True) pylab.legend(eltyps, loc="lower right") pylab.tight_layout() pylab.savefig("solid.svg", format="svg")
def modality(handle, cutoff, resolution): """ """ x, y = zip(*map(lambda x: map(int, x.split()), handle.readlines()[:cutoff])) # Ad-hoc weighing function. w = map(lambda x: 1.0 / (10 * x + 1), x) # Get an approximation of the distribution. f = interpolate.UnivariateSpline(x, y, w=w) xs = pylab.linspace(0, cutoff, resolution) # Plot the original. pylab.plot(x, y) # Plot the interpolated function. ys = f(xs) pylab.plot(xs, ys) # Plot the tops. ys = f(xs, 1) g = interpolate.InterpolatedUnivariateSpline(xs, ys) pylab.plot(g.roots(), f(g.roots()), 'o') # Plot the bending points. ys = f(xs, 2) g = interpolate.InterpolatedUnivariateSpline(xs, ys) pylab.plot(g.roots(), f(g.roots()), 'o') pylab.legend(('original', 'interpolated', '1st derivative', '2nd derivative'), loc='best') pylab.xscale("log") pylab.yscale("log") pylab.show()
def plot(self, response, label=None, clip=-80, nharmonics=8, spectrum=None, freq_range=None): if freq_range is not None: lower_freq, upper_freq = freq_range else: lower_freq = upper_freq = None if lower_freq is None: lower_freq = self.start_freq if upper_freq is None: upper_freq = self.stop_freq if self.has_harmonics() and nharmonics > 1 and (spectrum is None or spectrum): lines = self.plot_harmonic_spectrum( response, nharmonics=nharmonics, lower_freq=lower_freq, upper_freq=upper_freq ) pylab.xlim(left=lower_freq, right=upper_freq) for i, line in enumerate(lines): if label: line.set_label("%d, %s" % (i + 1, label)) else: line.set_label("%d" % (i + 1)) return lines elif (spectrum is None and self.has_spectrum()) or spectrum: f = numpy.logspace(numpy.log10(lower_freq), numpy.log10(upper_freq), 200) h = self.get_spectrum(response, 2 * numpy.pi * f / self.fs) s = 20 * numpy.log10(abs(h)) lines = pylab.plot(f, numpy.where(s > clip, s, numpy.nan), label=label) pylab.xscale("log") return lines else: return pylab.plot(self.timeline, response, label=label)
def main(): # gutenberg gu_words = gutenberg.words() gu_words_exclude_stops = exclude_stopwords(gu_words) gu_fd1 = get_frequency_distribution(gu_words) gu_fd2 = get_frequency_distribution(gu_words_exclude_stops) pylab.plot(gu_fd1, color='red') pylab.plot(gu_fd2, color='orange') # inaugural in_words = inaugural.words() in_words_exclude_stops = exclude_stopwords(in_words) in_fd1 = get_frequency_distribution(in_words) in_fd2 = get_frequency_distribution(in_words_exclude_stops) pylab.plot(in_fd1, color='black') pylab.plot(in_fd2, color='gray') # reuters yen_words = reuters.words(categories='yen') yen_words_exclude_stops = exclude_stopwords(yen_words) yen_fd1 = get_frequency_distribution(yen_words) yen_fd2 = get_frequency_distribution(yen_words_exclude_stops) pylab.plot(yen_fd1, color='blue') pylab.plot(yen_fd2, color='green') pylab.xscale('log') pylab.yscale('log') pylab.show()
def plot_bins(Y, loglog, logbins, suffix): X1, Y1, X2, Y2, alpha = fit_data(Y, True, pdf=True) pylab.figure(figsize=(7.5, 7)) pylab.rcParams.update({'font.size': 20}) pylab.scatter(X1, Y1) pylab.plot(X2, Y2, '--') bounds = get_bounds(X1, Y1, loglog, loglog) if loglog: pylab.xscale('log') pylab.yscale('log') xtext = numpy.exp(numpy.log(bounds[0])+(numpy.log(bounds[1])-numpy.log(bounds[0]))*0.65) ytext = numpy.exp(numpy.log(bounds[2])+(numpy.log(bounds[3])-numpy.log(bounds[2]))*0.65) else: xtext = (bounds[0]+bounds[1])/2.0 ytext = (bounds[2]+bounds[3])/2.0 pylab.axis(bounds) pylab.text(xtext, ytext, '$gamma$='+'{0:.2f}'.format(alpha)) pylab.xlabel('Change') pylab.ylabel('Density') pylab.tight_layout() pylab.show()
def plot(self, ylog10scale = False, timescale = "years", year = 25): """ Generate figure and axis for the population structure timescale choose from "2N0", "4N0", "generation" or "years" """ time = self.Time pop = self.pop for i in range(1,len(self.pop)): if type(pop[i]) == type(""): # ignore migration commands, and replace by (unchanged) pop size pop[i] = pop[i-1] if time[0] != 0 : time.insert(0, float(0)) pop.insert(0, float(1)) if timescale == "years": time = [ti * 4 * self.scaling_N0 * year for ti in time ] pl.xlabel("Time (years, "+`year`+" years per generation)", fontsize=20) #pl.xlabel("Years") elif timescale == "generation": time = [ti * 4 * self.scaling_N0 for ti in time ] pl.xlabel("Generations)") elif timescale == "4N0": time = [ti*1 for ti in time ] pl.xlabel("Time (4N generations)") elif timescale == "2N0": time = [ti*2 for ti in time ] pl.xlabel("Time (2N generations)") else: print "timescale must be one of \"4N0\", \"generation\", or \"years\"" return time[0] = time[1] / float(20) time.append(time[-1] * 2) yaxis_scaler = 10000 pop = [popi * self.scaling_N0 / float(yaxis_scaler) for popi in pop ] pop.insert(0, pop[0]) pl.xscale ('log', basex = 10) #pl.xlim(min(time), max(time)) pl.xlim(1e3, 1e7) if ylog10scale: pl.ylim(0.06, 10000) pl.yscale ('log', basey = 10) else: pl.ylim(0, max(pop)+2) pl.ylim(0,5) pl.tick_params(labelsize=20) #pl.step(time, pop , color = "blue", linewidth=5.0) pl.step(time, pop , color = "red", linewidth=5.0) pl.grid() #pl.step(time, pop , color = "black", linewidth=5.0) #pl.title ( self.case + " population structure" ) #pl.ylabel("Pop size ($*$ "+`yaxis_scaler` +")") pl.ylabel("Effective population size",fontsize=20 )
def _show_rates(rate, wo, wt, attenuator, tau_NP, tau_P): import pylab # pylab.figure() pylab.errorbar(rate, wt[0], yerr=wt[1], fmt="g.", label="attenuated") pylab.errorbar(rate, wo[0], yerr=wo[1], fmt="b.", label="unattenuated") pylab.xscale("log") pylab.yscale("log") pylab.xlabel("incident rate (counts/second)") pylab.ylabel("observed rate (counts/second)") pylab.legend(loc="best") pylab.grid(True) pylab.plot(rate, rate / attenuator, "g-", label="target") pylab.plot(rate, rate, "b-", label="target") Ipeak, Rpeak = peak_rate(tau_NP=tau_NP, tau_P=tau_P) if rate[0] <= Ipeak <= rate[-1]: pylab.axvline(x=Ipeak, ls="--", c="b") pylab.text( x=Ipeak, y=0.05, s=" %g" % Ipeak, ha="left", va="bottom", transform=pylab.gca().get_xaxis_transform() ) if False: pylab.axhline(y=Rpeak, ls="--", c="b") pylab.text( y=Rpeak, x=0.05, s=" %g\n" % Rpeak, ha="left", va="bottom", transform=pylab.gca().get_yaxis_transform() )
def plot_fas(freqs, ns_data, ew_data, eas_smoothed_data, fas_plot, station): """ Create a plot of both FAS components """ # Generate plot # Set plot dims pylab.gcf().set_size_inches(11, 8.5) pylab.gcf().clf() # Adjust title y-position t = pylab.title("Station: %s" % (station), size=12) pylab.plot(freqs, ns_data, 'b', lw=0.75, label="NS") pylab.plot(freqs, ew_data, 'r', lw=0.75, label="EW") pylab.plot(freqs, eas_smoothed_data, 'k', lw=1.25, label="Smoothed EAS") pylab.legend(loc='upper right') pylab.xscale('log') pylab.yscale('log') pylab.ylabel('Fourier Amplitude (cm/s)') pylab.xlabel('Frequency (Hz)') pylab.axis([0.01, 100, 0.001, 1000]) pylab.grid(True) pylab.grid(b=True, which='major', linestyle='-', color='lightgray') pylab.grid(b=True, which='minor', linewidth=0.5, color='gray') # Save plot pylab.savefig(fas_plot, format="png", transparent=False, dpi=plot_config.dpi) pylab.close()
def plot_population(population): # ADW: DEPRECATED: 2019-09-01 pylab.figure() #pylab.scatter(lon, lat, c=distance_modulus, s=500 * half_light_radius) #pylab.colorbar() pylab.scatter(lon, lat, edgecolors='none') xmin, xmax = pylab.xlim() # Reverse azimuthal axis pylab.xlim([xmax, xmin]) pylab.title('Random Positions in Survey Footprint') pylab.xlabel('Longitude (deg)') pylab.ylabel('Latitude (deg)') pylab.figure() pylab.scatter(stellar_mass, distance, c=r_physical, s=500 * r_physical, edgecolors='none') pylab.xscale('log') pylab.yscale('log') pylab.xlim([0.5 * range_stellar_mass[0], 2. * range_stellar_mass[1]]) pylab.colorbar() pylab.title('Half-light Radius (arcmin)') pylab.xlabel('Stellar Mass (arcmin)') pylab.ylabel('Distance (kpc)')
def filterresponse(b,a,fs=44100,scale='log',**kwargs): w, h = freqz(b,a) pl.subplot(2,1,1) pl.title('Digital filter frequency response') pl.plot(w/max(w)*fs/2, 20 * np.log10(abs(h)),**kwargs) pl.xscale(scale) # if scale=='log': # pl.semilogx(w/max(w)*fs/2, 20*np.log10(np.abs(h)), 'k') # else: # pl.plot(w/max(w)*fs/2, 20*np.log10(np.abs(h)), 'k') pl.ylabel('Gain (dB)') pl.xlabel('Frequency (rad/sample)') pl.axis('tight') pl.grid() pl.subplot(2,1,2) angles = np.unwrap(np.angle(h)) if scale=='log': pl.semilogx(w/max(w)*fs/2, angles, **kwargs) else: pl.plot(w/max(w)*fs/2, angles, **kwargs) pl.ylabel('Angle (radians)') pl.grid() pl.axis('tight') pl.xlabel('Frequency (rad/sample)')
def plot_eb_mode(gp_class, rep='', save=False, exp="0"): plt.figure(figsize=(10, 6)) plt.subplots_adjust(bottom=0.12, top=0.95, right=0.99) plt.scatter(np.exp(gp_class.logr), gp_class.xie, s=20, alpha=1, c='b', label='E-mode') plt.scatter(np.exp(gp_class.logr), gp_class.xib, s=20, alpha=1, c='r', label='B-mode') plt.plot(np.exp(gp_class.logr), np.zeros_like(gp_class.logr), 'k--', alpha=0.5, zorder=0) MIN = np.min([np.min(gp_class.xie), np.min(gp_class.xib)]) MAX = np.max([np.max(gp_class.xie), np.max(gp_class.xib)]) plt.ylim(-40, 60) plt.xlim(0.005, 1.5) plt.xscale('log') plt.xticks(size=16) plt.yticks(size=16) plt.xlabel('$\Delta \\theta$ (degree)', fontsize=22) plt.ylabel('$\\xi_{E/B}$ (mas$^2$)', fontsize=22) plt.title('%s %s' % ((gp_class.visit_id, gp_class.exp_id)), fontsize=20) plt.legend(loc=1, fontsize=16) if save: namefig = os.path.join(rep, 'eb_mode_%i.pdf' % int(exp)) plt.savefig(namefig, transparent=True)
def mesh2d_mcolor_mask(self, data, axis, output=None, mask=None, datscale='log', axiscale=['log', 'log'], pcolors='Greys', maskcolors=None): """ >>> generate 2D mesh plot <<< """ pl.clf() fig=pl.figure() ax=fig.add_subplot(111) pldat=data # get the color norm if(datscale=='log'): cnorm=colors.LogNorm() elif(datscale=='linear'): cnorm=colors.NoNorm() else: raise Exception color1=colors.colorConverter.to_rgba('white') color2=colors.colorConverter.to_rgba('blue') color3=colors.colorConverter.to_rgba('yellow') my_cmap0=colors.LinearSegmentedColormap.from_list('mycmap0',[color1, color1, color2, color2, color2, color3, color3], 512) my_cmap0._init() if pcolors!=None: cm=ax.pcolormesh(axis[0,:], axis[1,:], pldat, cmap=pl.cm.get_cmap(pcolors), norm=cnorm) #cm=ax.pcolormesh(axis[0,:], axis[1,:], pldat, cmap=my_cmap0, norm=cnorm) else: cm=ax.pcolormesh(axis[0,:], axis[1,:], pldat, norm=cnorm) if mask!=None: # get the color map of mask """ color1=colors.colorConverter.to_rgba('white') color2=colors.colorConverter.to_rgba('red') my_cmap=colors.LinearSegmentedColormap.from_list('mycmap',[color1, color2], 512) my_cmap._init() alphas=np.linspace(0.2, 0.7, my_cmap.N+3) my_cmap._lut[:,-1] = alphas """ maskdata=np.ma.masked_where((mask<=1e-2)&(mask>=-1e-2) , mask) mymap=ax.contourf(axis[0,:], axis[1,:], maskdata, cmap=maskcolors) cbar=fig.colorbar(mymap, ticks=[4, 6, 8]) #, orientation='horizontal') cbar.ax.set_yticklabels(['void', 'filament', 'halo']) pl.xscale(axiscale[0]) pl.yscale(axiscale[1]) return
def check_integrals(): k, pk = read_power_spectrum(non_linear='regpt') scales = [1., 3., 10., 30., 100.] plt.figure() for i_scale, scale in enumerate(scales): win_radial = window(k, 200., 200 + scale, 1.) win_transv = window(k, 200., 200., np.cos(scale / 200.)) full_int_radial = np.trapz(win_radial * pk, x=k) full_int_transv = np.trapz(win_transv * pk, x=k) i_k = np.arange(k.size // 2, k.size) int_radial = np.zeros(i_k.size) int_transv = np.zeros(i_k.size) kmax = k[i_k] for j, i in enumerate(i_k): int_radial[j] = np.trapz(win_radial[:i] * pk[:i], x=k[:i]) int_transv[j] = np.trapz(win_transv[:i] * pk[:i], x=k[:i]) plt.plot(kmax, int_radial / full_int_radial - 1, color=f'C{i_scale}', ls='--', label=f'dr = {scale}') plt.plot(kmax, int_transv / full_int_transv - 1, color=f'C{i_scale}', ls=':') plt.legend() plt.xlabel(r'$k_{\rm max}$ [h/Mpc]') plt.ylabel(r'Relative error on $C_{ij}$') plt.ylim(-1, 1) plt.xscale('log')
def test_plot_schechter(): phiStar = 1.8e-3 MStar = -20.04 alpha = -1.71 LStar = magnitudes.L_nu_from_magAB(MStar) mags = numpy.arange(-22, -11.0, 0.5) lums = magnitudes.L_nu_from_magAB(mags) phi_L = schechterL(lums, phiStar, alpha, LStar) phi_M = schechterM(mags, phiStar, alpha, MStar) L_L = schechterCumuLL(lums, phiStar, alpha, LStar) L_M = schechterCumuLM(mags, phiStar, alpha, MStar) phi_L_func = lambda l: l * schechterL(l, phiStar, alpha, LStar) L_L_num = utils.logquad(phi_L_func, lums, 1e35)[0] L_L_num2 = utils.vecquad(phi_L_func, lums, 1e29)[0] phi_M_func = lambda m: (magnitudes.L_nu_from_magAB(m) * schechterM(m, phiStar, alpha, MStar)) L_M_num2 = utils.vecquad(phi_M_func, -25, mags)[0] Ltot_L = schechterTotLL(phiStar, alpha, LStar) Ltot_M = schechterTotLM(phiStar, alpha, MStar) pylab.figure() pylab.subplot(221) pylab.plot(lums, lums * lums * phi_L) pylab.xscale('log') pylab.yscale('log') pylab.ylabel(r'$ L^2 \Phi_L$') pylab.subplot(222) pylab.plot(mags, -mags * lums * phi_M) pylab.yscale('log') pylab.ylabel(r'$ -M L \Phi_M$') pylab.subplot(223) pylab.plot(lums, Ltot_L - L_L) pylab.plot(lums, L_M) pylab.plot(lums, L_L_num, '--') pylab.plot(lums, L_L_num2, ':') pylab.plot(lums, L_M_num2, 'x') pylab.axhline(y=Ltot_L) pylab.axhline(y=Ltot_M) pylab.xscale('log') pylab.yscale('log') pylab.subplot(224) pylab.plot(mags, Ltot_M - L_M) pylab.plot(mags, L_L) pylab.plot(mags, L_L_num, '--') pylab.plot(mags, L_L_num2, ':') pylab.plot(mags, L_M_num2, 'x') pylab.axhline(y=Ltot_L) pylab.axhline(y=Ltot_M) pylab.yscale('log')
def plot(self): f = pylab.figure(figsize=(8,4)) co = [] #colors container for label, (pVal, logratio) in self.data.get(["pValue", "log2Ratio"]).iterrows(): if pVal < self.pCut: if logratio > 0: co.append(Colors().redColor) elif logratio < 0: co.append(Colors().greenColor) else: raise Exception else: co.append(Colors().blueColor) #print "Probability this is from a normal distribution: %.3e" %stats.normaltest(self.log2Ratio)[1] #ax = f.add_subplot(121) #pylab.axvline(self.meanLog2Ratio, color=Colors().redColor) #pylab.axvspan(self.meanLog2Ratio-(2*self.stdLog2Ratio), # self.meanLog2Ratio+(2*self.stdLog2Ratio), color=Colors().blueColor, alpha=0.2) #his = pylab.hist(self.log2Ratio, bins=50, color=Colors().blueColor) #pylab.xlabel("log2 Ratio %s/%s" %(self.sampleNames[1], self.sampleNames[0])) #pylab.ylabel("Frequency") ax = f.add_subplot(111, aspect='equal') pylab.scatter(self.genes1, self.genes2, c=co, alpha=0.5) pylab.ylabel("%s RPKM" %self.sampleNames[1]) pylab.xlabel("%s RPKM" %self.sampleNames[0]) pylab.yscale('log') pylab.xscale('log') pylab.tight_layout()
def plot_percentage(women_percentage, men_percentage, colors, xaxis_values, filename): """ plots the percentage of people who show up in N language editions :param men: :param women: :param colors: :return: """ fig = plt.figure(figsize=(6,6)) if len(colors) == 0: plt.gca().set_color_cycle(['pink', 'blue', 'yellow', 'red', 'black']) else: plt.gca().set_color_cycle(colors) #print xaxis_values #print women_percentage #print len(xaxis_values) #print len(women_percentage) plt.plot(xaxis_values, women_percentage[:len(xaxis_values)], linewidth=1) plt.plot(xaxis_values, men_percentage[:len(xaxis_values)], linewidth=1) plt.xlabel("Log Num Editions") plt.ylabel("Log Proportion") plt.xscale("log") plt.yscale("log") #plt.ysca:len(xaxis_values)lotle("log") plt.savefig(filename) plt.close()
def plot_tmp_imp( name_plot ): # distance between axes and ticks pl.rcParams['xtick.major.pad']='8' pl.rcParams['ytick.major.pad']='8' # set latex font pl.rc('text', usetex=True) pl.rc('font', **{'family': 'serif', 'serif': ['Computer Modern'], 'size': 20}) # plotting x_plf = pow(10,pl.linspace(-6,0,1000)) pl.clf() p_pl, = pl.plot(x_plf,ff_pl(x_plf,par_pl[0],par_pl[1]), ls='--', color='Red') p_lg, = pl.plot(x_plf,ff_lg(x_plf,par_lg[0],par_lg[1]), ls='-', color='RoyalBlue') p_points, = pl.plot(df_imp_1d.pi,df_imp_1d.imp,'.', color='Black',ms=10) pl.xscale('log') pl.yscale('log') pl.xlabel('$\phi$') pl.ylabel('$\mathcal{I}_{tmp}(\Omega=\{ \phi \})$') pl.grid() pl.axis([0.00001,1,0.0001,0.1]) leg_1 = '$\hat{Y} = $' + str("%.4f" % round(par_pl[0],4)) + '$\pm$' + str("%.4f" % round(vv_pl[0][0],4)) + ' $\hat{\delta} = $' + str("%.4f" % round(par_pl[1],4)) + '$\pm$' + str("%.4f" % round(vv_pl[1][1],4)) + ' $E_{RMS} = $' + str("%.4f" % round(pl.sqrt(chi_pl/len(df_imp_1d.imp)),4)) leg_2 = '$\hat{a} = $' + str("%.3f" % round(par_lg[0],3)) + '$\pm$' + str("%.3f" % round(vv_lg[0][0],3)) + ' $\hat{b} = $' + str("%.0f" % round(par_lg[1],3)) + '$\pm$' + str("%.0f" % round(vv_lg[1][1],3)) + ' $E_{RMS} = $' + str("%.4f" % round(pl.sqrt(chi_lg/len(df_imp_1d.imp)),4)) l1 = pl.legend([p_pl,p_lg], ['$f(\phi) = Y\phi^{\delta}$', '$g(\phi)= a \log_{10}(1+b\phi)$'], loc=2, prop={'size':15}) l2 = pl.legend([p_pl,p_lg], [leg_1 ,leg_2 ], loc=4, prop={'size':15}) pl.gca().add_artist(l1) pl.subplots_adjust(bottom=0.15) pl.subplots_adjust(left=0.17) pl.savefig("../plot/" + name_plot + ".pdf")
def makeComp(save=0): data = Repeatability.getRepeatsData() dc = data['dc_min'] dv = data['dv'] P.figure() P.plot( dc, dv, 'k.', alpha=0.4) P.ylim(0.1, 1e6) P.xlim(1e-6, 1) P.xscale('log') P.yscale('log') ylim = P.ylim() P.plot( [1e-2, 1e-2], ylim, 'b--', lw=2) P.plot( [5e-3, 5e-3], ylim, 'r--', lw=2) P.plot( [1e-6, 1], [1000, 1000], 'm--', lw=2) P.xlabel(r'$\Delta \chi^2/dof$') P.ylabel(r'$\Delta v$ (km/s)') P.tight_layout() if save: P.savefig(Repeatability.directory+'/plots/Repeat_all_rchi2_vel.pdf',\ bbox_inches='tight') ngals = len(dv)*1. print 'Total galaxies in plot', ngals print ' dchi2 < 0.01', N.sum( dc< 0.01), N.sum( dc< 0.01)/ngals print ' dchi2 < 0.005', N.sum( dc< 0.005), N.sum( dc< 0.005)/ngals print ' dv > 1000 km/s', N.sum( dv > 1000.), N.sum( dv > 1000.)/ngals return data
def flipPlot(minExp, maxExp): """Assumes minExp and maxExp positive integers: minExp < maxExp Plot results of 2**minExp to 2** maxExp coin flips""" ratios = [] diffs = [] xAxis = [] for exp in range(minExp, maxExp + 1): xAxis.append(2**exp) for numFlips in xAxis: numHeads = 0 for n in range(numFlips): if random.random() < 0.5: numHeads += 1 numTails = numFlips - numHeads ratios.append(numHeads / float(numTails)) diffs.append(abs(numHeads - numTails)) pylab.title('Difference Between Heads and Tails') pylab.grid(True) pylab.xlabel('Number of Flips') pylab.ylabel('Abs(#Heads - #Tails)') pylab.plot(xAxis, diffs, 'bo') pylab.xscale('log') pylab.yscale('log') pylab.savefig('heads_tails_difference.png') pylab.figure() pylab.grid(True) pylab.title('Heads/Tails Ratios') pylab.xlabel('Number of Flips') pylab.ylabel('#Heads/#Tails') pylab.plot(xAxis, ratios, 'bo') pylab.xscale('log') pylab.savefig('heads_tails_ratio.png')
def con(text, stopwords): alfa = [] content = [w for w in text if w.lower() not in stopwords and w.isalpha()] fdist = FreqDist(content) keys = fdist.keys() vals = fdist.values() maxiFreq = vals[0] for i in range(1, maxiFreq + 1): k = len([w for w in keys if fdist[w] == i]) alfa.append(k) ys = range(1, maxiFreq + 1) xs = alfa pylab.xlabel("Anzahl der Woerter") pylab.ylabel("Haeufigkeit") pylab.plot(xs, ys) pylab.show() pylab.xlabel("Anzahl der Woerter log scale") pylab.ylabel("Haeufigkeit log scale") pylab.plot(xs, ys) pylab.xscale('log') pylab.yscale('log') pylab.show() return alfa
def test_recover_gs_vary_n(Q,baselines,lms): """ This function runs many tests of the linear regression, varying the amount of noise introduced into the data. I hard-coded the global signal strength to be 1 so that it is easy to compare the magnitude of the recovered and true global signals and the amplitude of the noise. """ for jj in n.arange(100): gs_diff = n.zeros(20,dtype=complex) errors = n.zeros(20) n_sigs = n.logspace(-3,1,num=20) print n_sigs for ii,n_sig in enumerate(n_sigs): print ii gs_true,gs_recov,err = test_recover_gs(Q,baselines,lms,n_sig=n_sig) print gs_true print gs_recov print gs_true.shape gs_diff[ii] = gs_recov[0] - gs_true[0] errors[ii] = err p.scatter(n_sigs,n.absolute(gs_diff)) p.scatter(n_sigs,errors,color="red") p.xscale('log') p.yscale('log') p.xlim(1e-4,1e2) p.xlabel('Amplitude of noise relative to global signal\n(I.e. true global signal amplitude is 1)') #p.ylabel('Recovered global signal (true gs = 1)') p.ylabel('Difference between true and recovered global signal') #p.show() p.savefig('./figures/circle10_Q_pinv_gs_diff_vs_n.pdf') p.clf()
def test_fit_bb(self): def func(nu, T): return np.pi * rf.planck(nu, T, inp="Hz", out="freq") self.sp.cut_flux(max(self.sp.Flux) * 1e-5) freq = self.sp.Freq flux = self.sp.Flux Tinit = 1.e4 popt, pcov = curve_fit(func, freq, flux, p0=Tinit) Tbest = popt # bestT, pcov = curve_fit(rf.fit_planck(nu, inp='Hz'), nu, flux, p0=Tinit, sigma=sigma) sigmaT = np.sqrt(np.diag(pcov)) print 'True model values' print ' Tbb = %.2f K' % self.sp.T print 'Parameters of best-fitting model:' print ' T = %.2f +/- %.2f K' % (Tbest, sigmaT) # Tcol = self.sp.temp_color ybest = np.pi * rf.planck(freq, Tbest, inp="Hz", out="freq") # plot the solution plt.plot(freq, flux, 'b*', label='Spectral T: %f' % self.sp.T) plt.plot(freq, ybest, 'r-', label='Best Tcol: %f' % Tbest) plt.xscale('log') plt.yscale('log') plt.legend(loc=3) plt.show() self.assertAlmostEqual(Tbest, self.sp.T, msg="For planck Tcolor [%f] should be equal sp.T [%f]." % (Tbest, self.sp.T), delta=Tbest*0.01)
def draw_t1err_curve(pv_thresholds, t1err, label, num_trials): import pylab pylab.plot(pv_thresholds, t1err, "-o", label=label) pylab.yscale("log") pylab.xscale("log") pylab.xlabel(r"$\alpha$", fontsize="large") pylab.ylabel("type I error", fontsize="large") pylab.grid(True) pylab.xlim([1e-6, 1e-3]) pylab.ylim([1e-6, 1e0]) rt = pv_thresholds[::-1] import scipy.stats as stats lower = [ max(1e-7, (stats.distributions.binom.ppf(0.025, num_trials, t) - 1) / float(num_trials)) for t in rt ] upper = [ stats.distributions.binom.ppf(0.975, num_trials, t) / float(num_trials) for t in rt ] pylab.fill_between(rt, lower, upper, alpha=0.7, facecolor='#DDDDDD') pylab.plot(pv_thresholds, pv_thresholds, 'k--') pylab.legend(loc="lower right")
def flip_plot_log(min_exp, max_exp): """Assumes min_exp and max_exp positive integers; min_exp < max_exp Plots results of 2**min_exp to 2**max_exp coin flips""" ratios, diffs, x_axis = [], [], [] for exp in range(min_exp, max_exp + 1): x_axis.append(2**exp) for num_flips in x_axis: num_heads = 0 for n in range(num_flips): if random.choice(('H', 'T')) == 'H': num_heads += 1 num_tails = num_flips - num_heads try: ratios.append(num_heads / num_tails) diffs.append(abs(num_heads - num_tails)) except ZeroDivisionError: continue pylab.title('Difference Between Heads and Tails') pylab.xlabel('Number of Flips') pylab.xscale('log') pylab.ylabel('Abs(#Heads - #Tails)') pylab.yscale('log') pylab.plot(x_axis, diffs, 'ko') # original code had 'k' in text, # then it was changed to 'ko' to get rid of the lines pylab.figure() pylab.title('Heads/Tails Ratios') pylab.xlabel('Number of Flips') pylab.xscale('log') pylab.ylabel('#Heads/#Tails') pylab.plot(x_axis, ratios, 'ko') # same with the 'ko' replacing 'k'
def plotCumulativeRegrets(names, cumulativerewards_, timeHorizon, testName="riverSwim", semilog=False, ysemilog=False): #print(len(cumulativerewards_[0]), len(cumulativerewards_))#[0])#print(len(cumulativerewards_[0]), cumulativerewards_[0]) nbFigure = pl.gcf().number + 1 pl.figure(nbFigure) cur_dir = os.path.abspath(os.path.curdir) output_path = os.path.join(cur_dir, 'results') textfile = output_path + "/Regret-" colors = [ 'black', 'blue', 'gray', 'green', 'red' ] #['black', 'purple', 'blue','cyan','yellow', 'orange', 'red', 'chocolate'] avgcum_rs = [ np.mean(cumulativerewards_[-1], axis=0) - np.mean(cumulativerewards_[i], axis=0) for i in range(len(cumulativerewards_) - 1) ] std_cum_rs = [ 1.96 * np.std(cumulativerewards_[i], axis=0) / np.sqrt(len(cumulativerewards_[i])) for i in range(len(cumulativerewards_) - 1) ] for i in range(len(cumulativerewards_) - 1): pl.plot(avgcum_rs[i], label=names[i], color=colors[i % len(colors)]) step = timeHorizon // 10 pl.errorbar(np.arange(0, timeHorizon, step), avgcum_rs[i][0:timeHorizon:step], std_cum_rs[i][0:timeHorizon:step], color=colors[i % len(colors)], linestyle='None', capsize=10) textfile += names[i] + "-" print(names[i], ' has regret ', avgcum_rs[i][-1], ' after ', len(avgcum_rs[i]), ' time steps with variance ', std_cum_rs[i][-1]) #pl.show() pl.legend() pl.xlabel("Time steps", fontsize=13, fontname="Arial") pl.ylabel("Regret", fontsize=13, fontname="Arial") pl.ticklabel_format(axis='both', useMathText=True, useOffset=True, style='sci', scilimits=(0, 0)) if semilog: pl.xscale('log') textfile += "_xsemilog" else: pl.xlim(0, timeHorizon) if ysemilog: pl.yscale('log') textfile += "_ysemilog" pl.ylim(100) else: pl.ylim(0) pl.savefig(textfile + testName + '.png')
def plot_values(X, Y, xlabel, ylabel, suffix): output_filename = constants.CHARTS_FOLDER_NAME + constants.DATASET + '_' + suffix pylab.figure(figsize=(8, 7)) pylab.rcParams.update({'font.size': 20}) pylab.scatter(X, Y) ''' #smoothing s = np.square(np.max(Y)) tck = interpolate.splrep(X, Y, s=s) Y_smooth = interpolate.splev(X, tck) pylab.plot(X, Y_smooth) ''' #pylab.axis(vis.get_bounds(X, Y, False, False)) pylab.xscale('log') pylab.yscale('log') pylab.xlabel(xlabel) pylab.ylabel(ylabel) #pylab.tight_layout() pylab.savefig(output_filename + '.pdf')
def myBenchmark(myestimator,title): n = 18 abserr = np.zeros((n,2*dimension)) sizearray = np.zeros((n)) size = 8 for i in range(n): sizearray[i] = size print("i=%d, size = %d" % (i, size)) sensitivityAnalysis = myestimator(distribution,size,model) first_order = sensitivityAnalysis.getFirstOrderIndices() total_order = sensitivityAnalysis.getTotalOrderIndices() abserr[i,0] = abs(first_order[0] - exact['S1']) abserr[i,1] = abs(first_order[1] - exact['S2']) abserr[i,2] = abs(first_order[2] - exact['S3']) abserr[i,3] = abs(total_order[0] - exact['ST1']) abserr[i,4] = abs(total_order[1] - exact['ST2']) abserr[i,5] = abs(total_order[2] - exact['ST3']) size = size * 2 # Figure pl.figure() pl.plot(sizearray,abserr[:,0],"-",label="S1") pl.plot(sizearray,abserr[:,1],":",label="S2") pl.plot(sizearray,abserr[:,2],"--",label="S3") pl.plot(sizearray,abserr[:,3],"-+",label="ST1") pl.plot(sizearray,abserr[:,4],"-*",label="ST2") pl.plot(sizearray,abserr[:,5],"-^",label="ST3") pl.xlabel("Iterations") pl.ylabel("Absolute error") pl.legend() pl.xscale("log") pl.yscale("log") pl.title(title) pl.savefig(title + ".pdf") pl.savefig(title + ".png")
def show_plot(xlabel, ylabel, xlog=False, ylog=False): plt.xscale('log') if xlog else None plt.yscale('log') if ylog else None plt.xlabel(xlabel) plt.ylabel(ylabel) plt.subplot(111).legend() plt.show()
def _set_axis_parameter( self ): # set axis to equal length params = self.__params ax_0 = self._get_axis() # set axis aspect pylab.xlim(params['xlim']) pylab.ylim(params['ylim']) x0,x1 = ax_0.get_xlim() y0,y1 = ax_0.get_ylim() if params['xlog'] and params['ylog']: delta_x = float(np.log(x1)-np.log(x0)) delta_y = float(np.log(y1)-np.log(y0)) else: delta_x = float(x1 - x0) delta_y = float(y1 - y0) ax_0.set_aspect(delta_x/delta_y) # set tick size ax_0.tick_params(axis='both', labelsize=params['ticksize']) # set logarithmic scale if params['xlog']: pylab.xscale('log') if params['grid']: ax_0.xaxis.grid( True, which='both' ) if params['ylog']: pylab.yscale('log') if params['grid']: ax_0.yaxis.grid( True, which='both' ) # grid below bars and boxes ax_0.set_axisbelow(params['axisbelow'])
def plot_xy(cursor, query, prefix=None, color='b', marker='.', xlog=False, ylog=False, xlabel='', ylabel='', title=''): """ Executes the 'query' which should return two numerical columns. """ cursor.execute(query) x_list = [] y_list = [] for row in cursor: (x, y) = row if (x != None and y != None): x_list.append(x) y_list.append(y) X = pylab.array(x_list) Y = pylab.array(y_list) pylab.figure() pylab.hold(True) pylab.plot(X, Y, color=color, marker=marker, linestyle='None') if (xlog): pylab.xscale('log') if (ylog): pylab.yscale('log') pylab.title(title + " (R^2 = %.2f)" % pylab.corrcoef(X,Y)[0,1]**2) pylab.xlabel(xlabel) pylab.ylabel(ylabel) if (prefix != None): pylab.savefig('../res/%s.pdf' % prefix, format='pdf') pylab.hold(False)
def test_window(): ''' Reproduce Fig 4 of Johnson et al. 2014 even though his labels are switched between (a and e) and (b and d) ''' k = 10**np.linspace(-4, 0, 1000) plt.figure() #-- Values from Johnson et al. 2014 r0_r1_angle = [[86.6, 133.7, 0.393], [76.8, 127.6, 1.313], [59.16, 142.5, 0.356], [51.9, 91.1, 0.315], [99.449, 158.4, 1.463]] r0_r1_angle = [[50., 50., 0.], [50., 50., np.pi / 2], [50., 50., np.pi]] for win, alpha, ls in zip([window, window_2, window_3], [1, 0.5, 1.0], ['-', '--', ':']): #for win, alpha, ls in zip([window_2, window_3], [ 0.5, 1.0], [ '--', ':']): for i, [r0, r1, angle] in enumerate(r0_r1_angle): plt.plot(k, win(k, r0, r1, np.cos(angle)), color=f'C{i}', ls=ls, alpha=alpha) plt.legend() plt.xlim(5e-4, 2e-1) plt.xscale('log') plt.xlabel('k [h/Mpc]') plt.ylabel(r'$W_{i,j}(k)$')
def run_analysis(filename,mode,method): click.echo('Reading file : %s'%filename) data = IOfile.parsing_input_file(filename) click.echo('Creating class...') theclass = TFC(data) click.echo('Calculating transfer function using %s method'%method) if method=='tf_kramer286_sh': theclass.tf_kramer286_sh() elif method=='tf_knopoff_sh': theclass.tf_knopoff_sh() elif method=='tf_knopoff_sh_adv': theclass.tf_knopoff_sh_adv() plt.plot(theclass.freq,np.abs(theclass.tf[0]),label=method) plt.xlabel('frequency (Hz)') plt.ylabel('Amplification') plt.yscale('log') plt.xscale('log') plt.grid(True,which='both') plt.legend(loc='best',fancybox=True,framealpha=0.5) #plt.axis('tight') plt.autoscale(True,axis='x',tight=True) plt.tight_layout() plt.savefig('test.png', format='png') click.echo(click.style('Calculation has been finished!',fg='green'))
def plot_experiment(): for timestamp in TIMESTAMPS: throughputs = {} # all_averages = [] # lengend = [] # if TIMESTAMP_LABELS[timestamp] != "TMPFS": # continue for sub_experiment in SUB_EXPERIMENTS: # legend.append(sub_experiment) time_averages, std, data, throughputs_averages = get_sub_experiment_data(sub_experiment, timestamp) pylab.errorbar(data, throughputs_averages, yerr=std, fmt=EXPERIMENT_MARKER[sub_experiment], label=EXPERIMENT_LABELS[sub_experiment]) throughputs[sub_experiment] = list(throughputs_averages) # pylab.bar(data, throughputs_averages, 1000, yerr=std) overheads = [] for i in range(len(throughputs["python"])): overheads.append(float(throughputs["fpga"][i])/float(throughputs["python"][i])) overhead_sum = 0 for overhead in overheads: overhead_sum = overhead_sum + overhead overhead_average = overhead_sum/len(overheads) print "Overhead average: {}".format((1-overhead_average)*100.0) pylab.xscale("log", nonposx='clip') pylab.xlabel("Data Processed (bytes)") # pylab.ylabel("Time (s)") pylab.ylabel("Throughput (KB/s)") pylab.legend(loc=4) pylab.savefig("{}.png".format(TIMESTAMP_LABELS[timestamp])) pylab.savefig("{}.pdf".format(TIMESTAMP_LABELS[timestamp])) pylab.show()
def plot_per_sel(performance, selected, top, repeats, xlabel, ylabel, suffix): print suffix output_filename = constants.WISDOM_FOLDER_NAME + suffix pylab.figure(figsize=(15, 10)) pylab.rcParams.update({'font.size': 30}) X, Y = aggregate_per_sel(performance, selected, top, repeats, 'true', '0') pylab.plot(X, Y, linewidth=2, color="red", marker='o', markersize=15, markeredgecolor="red", markerfacecolor="white") X, Y = aggregate_per_sel(performance, selected, top, repeats, 'true', '1') pylab.plot(X, Y, linewidth=2, color="blue", marker='o', markersize=15, markeredgecolor="blue", markerfacecolor="white") X, Y = aggregate_per_sel(performance, selected, top, repeats, 'true', '-1') pylab.plot(X, Y, linewidth=2, color="green", marker='o', markersize=15, markeredgecolor="green", markerfacecolor="white") pylab.xscale('log', basex=10) pylab.xlabel(xlabel) pylab.ylabel(ylabel) pylab.legend(['Crowd', 'Network - 1', 'Network - Inf'], loc='upper left') pylab.tight_layout() pylab.savefig(output_filename + '.pdf')
def validatePredict(self, pred, flags_geometry, lon, lat, r_physical, abs_mag, distance): import matplotlib cmap = matplotlib.colors.ListedColormap(['Gold', 'Orange', 'DarkOrange', 'OrangeRed', 'Red']) pylab.figure() pylab.scatter(lon, lat, c=flags_geometry, s=10) pylab.colorbar() pylab.figure() pylab.xscale('log') pylab.scatter(1.e3 * r_physical[flags_geometry == 0], abs_mag[flags_geometry == 0], c=pred[flags_geometry == 0], vmin=0., vmax=1., s=10, cmap=cmap) pylab.colorbar().set_label('ML Predicted Detection Probability') pylab.xlim(1., 3.e3) pylab.ylim(6., -12.) pylab.xlabel('Half-light Radius (pc)') pylab.ylabel('M_V (mag)') pylab.figure() pylab.xscale('log') pylab.scatter(distance[flags_geometry == 0], abs_mag[flags_geometry == 0], c=pred[flags_geometry == 0], vmin=0., vmax=1., s=10, cmap=cmap) pylab.colorbar().set_label('ML Predicted Detection Probability') pylab.xlim(3., 600.) pylab.ylim(6., -12.) pylab.xlabel('Distance (kpc)') pylab.ylabel('M_V (mag)')
def zipf(text, name, new_figure=False, log=True): fdis = dict(FreqDist(text)) freq = [ item[1] for item in sorted(fdis.items(), key=lambda kv: kv[1], reverse=True) ] rank = [ item + 1 for item in range( len(sorted(fdis.items(), key=lambda kv: kv[1], reverse=True))) ] # plot freq vs rank using pylab # (plotting will occur on the same plot unless 'new_figure' parameter is 'True') if new_figure: pylab.figure() pylab.plot(rank, freq, label=name) # change plot to log scale to visually confirm Zipf's Law # see discussion in README.md if log: pylab.xscale("log") pylab.yscale("log") # add axis labels, title, and legend pylab.xlabel('Rank') pylab.ylabel('Frequency') pylab.title('Logorithmic Frequency vs Rank for Words in a Text') pylab.legend(loc='upper right')
def plot_eb_mode_single_visit(input_pkl, mas=3600. * 1e3, arcsec=3600., YLIM=[-20, 60], title="", read_python2=False): if read_python2: dic = pickle.load(open(input_pkl, 'rb'), encoding='latin1') else: dic = pickle.load(open(input_pkl, 'rb')) logr, xiplus, ximinus, xicross, xiz2 = vcorr(dic['u'], dic['v'], dic['du'] * mas, dic['dv'] * mas) xib = xiB(logr, xiplus, ximinus) xie = xiplus - xib plt.figure(figsize=(10, 6)) plt.subplots_adjust(bottom=0.13, top=0.93, left=0.12, right=0.99) plt.scatter(np.exp(logr) * 60, xie, c='b', label='E-mode') plt.scatter(np.exp(logr) * 60, xib, c='r', label='B-mode') plt.plot(np.exp(logr) * 60, np.zeros_like(logr), 'k--', zorder=0) plt.ylim(YLIM[0], YLIM[1]) plt.xlim(0.005 * 60, 1.5 * 60) plt.xscale('log') plt.xticks(size=20) plt.yticks(size=20) plt.xlabel('$\Delta \\theta$ (arcmin)', fontsize=24) plt.ylabel('$\\xi_{E/B}$ (mas$^2$)', fontsize=24) #plt.title(int(self.exp_id), fontsize=20) plt.title(title, fontsize=22) plt.legend(loc=1, fontsize=20)
def plot_cv_results(r2=None, r2_relaxed=None, nonzeros=None, corrs=None, corrs_relaxed=None, alphas=None, plot_var=False): # suppressing "mean of empty slice" warnings with warnings.catch_warnings(): warnings.simplefilter("ignore", category=RuntimeWarning) n = np.nanmean(nonzeros, axis=(0, 1)) cr = np.nanmean(r2_relaxed, axis=(0, 1)) c = np.nanmean(r2, axis=(0, 1)) c1 = np.nanmean(corrs_relaxed, axis=(0, 1))[:, :, 0] if corrs_relaxed.shape[4] > 1: c2 = np.nanmean(corrs_relaxed, axis=(0, 1)) if plot_var: with warnings.catch_warnings(): warnings.simplefilter("ignore", category=RuntimeWarning) n_std = np.nanstd(nonzeros, axis=(0, 1)) cr_std = np.nanstd(r2_relaxed, axis=(0, 1)) c_std = np.nanstd(r2, axis=(0, 1)) c1_std = np.nanstd(corrs_relaxed, axis=(0, 1))[:, :, 0] if corrs_relaxed.shape[4] > 1: c2_std = np.nanstd(corrs_relaxed, axis=(0, 1)) plt.figure(figsize=(9, 4)) plt.subplot(121) plt.plot(n, cr, '.-', linewidth=1) plt.gca().set_prop_cycle(None) if plot_var: plt.plot(n, cr + cr_std, '.-', linewidth=1, alpha=.2, label=None) plt.gca().set_prop_cycle(None) plt.plot(n, cr - cr_std, '.-', linewidth=1, alpha=.2, label=None) plt.gca().set_prop_cycle(None) plt.plot(n, c, '.--', linewidth=1, alpha=.5) #plt.gca().set_prop_cycle(None) #if plot_var: # plt.plot(n, c+c_std, '.-', linewidth=1, alpha=.2, label=None) # plt.gca().set_prop_cycle(None) # plt.plot(n, c-c_std, '.-', linewidth=1, alpha=.2, label=None) plt.xscale('log') plt.xlabel('Number of non-zero genes') plt.ylabel('Test R2') plt.legend(['$\\alpha=' + str(a) + '$' for a in alphas]) plt.subplot(122) plt.plot(n, c1, '.-', linewidth=1) if corrs_relaxed.shape[4] > 1: for k in range(1, corrs_relaxed.shape[4]): plt.gca().set_prop_cycle(None) plt.plot(n, c2[:, :, k], '.--', linewidth=1) plt.xscale('log') plt.xlabel('Number of non-zero genes') plt.ylabel('Correlations') plt.legend(alphas) plt.legend(['$\\alpha=' + str(a) + '$' for a in alphas]) plt.tight_layout()
def plot_percentage(women_percentage, men_percentage, colors, xaxis_values, filename): """ plots the percentage of people who show up in N language editions :param men: :param women: :param colors: :return: """ fig = plt.figure(figsize=(6, 6)) if len(colors) == 0: plt.gca().set_color_cycle(['pink', 'blue', 'yellow', 'red', 'black']) else: plt.gca().set_color_cycle(colors) #print xaxis_values #print women_percentage #print len(xaxis_values) #print len(women_percentage) plt.plot(xaxis_values, women_percentage[:len(xaxis_values)], linewidth=1) plt.plot(xaxis_values, men_percentage[:len(xaxis_values)], linewidth=1) plt.xlabel("Log Num Editions") plt.ylabel("Log Proportion") plt.xscale("log") plt.yscale("log") #plt.ysca:len(xaxis_values)lotle("log") plt.savefig(filename) plt.close()
def figStrategiesPropTo(titles,cost=1,scale='log',dim=1,noise=0): numE = 5 path = './data/' fig = plt.figure(1) fig.set_size_inches(3.3,2.5) ax = plt.subplot(1,1,1) minX = 100 i = -1 for tit in titles: i += 1 propLowHigh = np.loadtxt("./dataDE/EN_Oct19_propLowHigh_v4"+str(noise)+str(dim)+tit+".txt") ax.plot([1,3,10,30,100],propLowHigh[:,cost],marker='.',ms=10,label=ratio(tit),linewidth=1.5,color = cols[i]) t = propLowHigh[:,cost] minX = min(min(t[t>0]),minX) plt.xscale('log') plt.xlabel('Environmental Transition Rate',fontsize=10) plt.ylabel('Percentage of cells with \n high protein expression',fontsize=10) plt.yscale(scale) plt.ylim(minX/10.,120) plt.xlim(0.9,120) plt.legend(loc=4,frameon=0,fontsize=10,ncol=2) customaxis(ax, c_left='k', c_bottom='k', c_right='none', c_top='none', lw=1, size=10, pad=8) #plt.show() plt.show() plt.savefig("./imagesDE/lines"+tit[0]+str(cost)+str(noise)+str(dim)+tit[-2:]+'.pdf', bbox_inches='tight' ,dpi=100) plt.clf()
def rank_size_plot(data, attr, label, filename): plt.figure(figsize=(6, 6)) plt.subplot(111) men = data[data.gender == 'male'] rank_m = men[attr].sort(ascending=False, inplace=False) women = data[data.gender == 'female'] rank_w = women.edition_count.sort(ascending=False, inplace=False) plt.plot(np.arange(rank_m.shape[0], dtype=np.float) / rank_m.shape[0] + 0.001, rank_m, label='Men', linestyle='none', marker='.', alpha=0.5) plt.plot(np.arange(rank_w.shape[0], dtype=np.float) / rank_w.shape[0] + 0.001, rank_w, label='Women', linestyle='none', marker='.', alpha=0.5) plt.xlabel('Normalized Rank') plt.ylabel(label) plt.yscale('log') plt.xscale('log') plt.legend() plt.xlim([0.001, 1.001]) plt.savefig(filename, bbox_inches='tight')
def plot_lifetime(): U2 = 1 mN = np.linspace(0.5, 6.5, 20) #GeV y = [] for i in mN: print i y.append(get_tau0ns(i, U2) * 1e-9) #ns to s plt.figure() plt.xscale('log') plt.yscale('log') plt.title(r'lifetime, $U_{\mu N}^2$ = ' + str(U2)) plt.xlabel("$m_N$ [GeV]", fontsize=14) plt.ylabel('$tau_{0}$ [s]', fontsize=14) plt.plot(mN, y, color='sienna', linestyle='dashed', linewidth=0.8, label=r'') #plt.plot(M, BR2, color='orangered', linestyle = 'dashed',linewidth = 0.8,label=r'$N \rightarrow \mu^\pm K^\mp $') plt.legend() plt.savefig('lifetime_check.pdf')
def show_table(table_name,ls="none", fmt="o", legend=False, name="m", do_half=0): bt = fi.FITS(table_name)[1].read() rgpp = (np.unique(bt["rgp_lower"])+np.unique(bt["rgp_upper"]))/2 nbins = rgpp.size plt.xscale("log") colours=["purple", "forestgreen", "steelblue", "pink", "darkred", "midnightblue", "gray", "sienna", "olive", "darkviolet"] pts = ["o", "D", "x", "^", ">", "<", "1", "s", "*", "+", "."] for i,r in enumerate(rgpp): sel = (bt["i"]==i) snr = 10** ((np.log10(bt["snr_lower"][sel]) + np.log10(bt["snr_upper"][sel]))/2) if do_half==1 and i>nbins/2: continue elif do_half==2 and i<nbins/2: continue if legend: plt.errorbar(snr, bt["%s"%name][i*snr.size:(i*snr.size)+snr.size], bt["err_%s"%name][i*snr.size:(i*snr.size)+snr.size], color=colours[i], ls=ls, fmt=pts[i], lw=2.5, label="$R_{gpp}/R_p = %1.2f-%1.2f$"%(np.unique(bt["rgp_lower"])[i],np.unique(bt["rgp_upper"])[i])) else: plt.errorbar(snr, bt["%s"%name][i*snr.size:(i*snr.size)+snr.size], bt["err_%s"%name][i*snr.size:(i*snr.size)+snr.size], color=colours[i], ls=ls, fmt=pts[i], lw=2.5) plt.xlim(10,300) plt.axhline(0, lw=2, color="k") plt.xlabel("Signal-to-Noise $SNR_w$") if name=="m": plt.ylim(-0.85,0.05) plt.ylabel("Multiplicative Bias $m \equiv (m_1 + m_2)/2$") elif name=="alpha": plt.ylabel(r"PSF Leakage $\alpha \equiv (\alpha _1 + \alpha _2)/2$") plt.ylim(-0.5,2) plt.legend(loc="lower right")
def _set_axis_parameter(self): # set axis to equal length params = self.__params ax_0 = self._get_axis() # set axis aspect pylab.xlim(params['xlim']) pylab.ylim(params['ylim']) x0, x1 = ax_0.get_xlim() y0, y1 = ax_0.get_ylim() if params['xlog'] and params['ylog']: delta_x = float(np.log(x1) - np.log(x0)) delta_y = float(np.log(y1) - np.log(y0)) else: delta_x = float(x1 - x0) delta_y = float(y1 - y0) ax_0.set_aspect(delta_x / delta_y) # set tick size ax_0.tick_params(axis='both', labelsize=params['ticksize']) # set logarithmic scale if params['xlog']: pylab.xscale('log') if params['grid']: ax_0.xaxis.grid(True, which='both') if params['ylog']: pylab.yscale('log') if params['grid']: ax_0.yaxis.grid(True, which='both') # grid below bars and boxes ax_0.set_axisbelow(params['axisbelow'])
def _show_rates(rate, wo, wt, attenuator, tau_NP, tau_P): import pylab #pylab.figure() pylab.errorbar(rate, wt[0], yerr=wt[1], fmt='g.', label='attenuated') pylab.errorbar(rate, wo[0], yerr=wo[1], fmt='b.', label='unattenuated') pylab.xscale('log') pylab.yscale('log') pylab.xlabel('incident rate (counts/second)') pylab.ylabel('observed rate (counts/second)') pylab.legend(loc='best') pylab.grid(True) pylab.plot(rate, rate/attenuator, 'g-', label='target') pylab.plot(rate, rate, 'b-', label='target') Ipeak, Rpeak = peak_rate(tau_NP=tau_NP, tau_P=tau_P) if rate[0] <= Ipeak <= rate[-1]: pylab.axvline(x=Ipeak, ls='--', c='b') pylab.text(x=Ipeak, y=0.05, s=' %g'%Ipeak, ha='left', va='bottom', transform=pylab.gca().get_xaxis_transform()) if False: pylab.axhline(y=Rpeak, ls='--', c='b') pylab.text(y=Rpeak, x=0.05, s=' %g\n'%Rpeak, ha='left', va='bottom', transform=pylab.gca().get_yaxis_transform())
def std_mean_relationship(): path = '/Users/veronikasamborska/Desktop/photometry_code/code/data' files = os.listdir(path) mean_signal_corrected_list = [] std_list = [] plt.figure() for file in files: if 'p8-VTA-2018-04-20-142431.ppd' in file: data = di.import_data(file) OLS = LinearRegression() OLS.fit(data['ADC2_filt'][:, None], data['ADC1_filt'][:, None]) estimated_motion = OLS.predict(data['ADC2_filt'][:, None]).squeeze() corrected_signal = data['ADC1_filt'] - estimated_motion mean_signal_corrected = np.mean(data['ADC1']) std_signal_corrected = np.std(corrected_signal) mean_signal_corrected_list.append(mean_signal_corrected) std_list.append(std_signal_corrected) plt.xscale('linear') plt.scatter(mean_signal_corrected, std_signal_corrected) plt.pause(0.05) plt.xlabel('Mean Signal') plt.ylabel('Standard Deviationj of the Signal') z = np.polyfit(mean_signal_corrected_list, std_list, 1) p = np.poly1d(z) plt.plot(mean_signal_corrected_list, p(mean_signal_corrected_list), "r") plt.show()
def _plot_fits(data, theory, colors, labels, view): import pylab x, y, dy = data theory_x, theory_y = theory for k, color in enumerate(colors): pylab.errorbar(x, y[:, k], yerr=dy[:, k], fmt='.', color=color['base'], label='_') pylab.plot(theory_x, theory_y[:, k], '-', color=color['dark'], label=labels[k + 2]) # Note: no xlabel since it is supplied by the residual plot below this plot pylab.ylabel(labels[1]) if len(colors) > 1: pylab.legend() if view == 'log': pylab.xscale('linear') pylab.yscale('log') elif view == 'logx': pylab.xscale('log') pylab.yscale('linear') elif view == 'logy': pylab.xscale('linear') pylab.yscale('log') elif view == 'loglog': pylab.xscale('log') pylab.yscale('log') else: # view == 'linear' pylab.xscale('linear') pylab.yscale('linear')
def plot_xprofiles(self): #plotting abundance profiles fig = pl.figure() ax = fig.add_subplot(111) N = len(self.data['params']['atm_active_gases']+self.data['params']['atm_inactive_gases']) cols_mol = {} for mol_idx, mol_val in enumerate(self.data['params']['atm_active_gases']): cols_mol[mol_val] = self.cmap(float(mol_idx)/N) prof = self.data['data']['active_mixratio_profile'][mol_idx] if mol_val in cols_mol: pl.plot(prof[:,1], prof[:,0]/1e5, color=cols_mol[mol_val], label=mol_val, ls='solid',linewidth=2.0) else: pl.plot(prof[:,1], prof[:,0]/1e5, color=self.cmap(float(len(self.data['params']['atm_active_gases'])+len(self.data['params']['atm_inactive_gases'])+mol_idx)/N), label=mol_val, ls='solid',linewidth=2.0) for mol_idx, mol_val in enumerate(self.data['params']['atm_inactive_gases']): prof = self.data['data']['inactive_mixratio_profile'][mol_idx] if mol_val in cols_mol: pl.plot(prof[:,1], prof[:,0]/1e5, color=cols_mol[mol_val], ls='dashed',linewidth=2.0) else: pl.plot(prof[:,1], prof[:,0]/1e5, color=self.cmap(float(len(self.data['params']['atm_active_gases'])+len(self.data['params']['atm_inactive_gases'])+mol_idx)/N), label=mol_val, ls='dashed',linewidth=2.0) pl.gca().invert_yaxis() pl.yscale('log') pl.xscale('log') pl.xlim(1e-12, 3) pl.xlabel('Mixing ratio') pl.ylabel('Pressure (bar)') pl.tight_layout() box = ax.get_position() ax.set_position([box.x0, box.y0, box.width * 0.8, box.height]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5), ncol=1, prop={'size':11}, frameon=False) pl.title('Mixing ratios', fontsize=14)
def satellitePopulation(mask, nside_pix, n, range_distance=[5., 500.], range_stellar_mass=[1.e1, 1.e6], range_r_physical=[1.e-3, 2.], plot=False): """ Create a population of n randomly placed satellites within a survey mask. Satellites are distributed uniformly in log(distance) (kpc), uniformly in log(stellar_mass) (M_sol), and uniformly in physical half-light radius log(r_physical) (kpc). The ranges can be set by the user. Returns the simulated area (deg^2) as well as the lon (deg), lat (deg), distance modulus, stellar mass (M_sol), and half-light radius (deg) for each satellite """ lon, lat, simulation_area = ugali.utils.skymap.randomPositions(mask, nside_pix, n=n) distance = 10**np.random.uniform(np.log10(range_distance[0]), np.log10(range_distance[1]), n) stellar_mass = 10**np.random.uniform(np.log10(range_stellar_mass[0]), np.log10(range_stellar_mass[1]), n) # Physical half-light radius (kpc) r_physical = 10**np.random.uniform(np.log10(range_r_physical[0]), np.log10(range_r_physical[1]), n) #half_light_radius = np.degrees(np.arcsin(half_light_radius_physical \ # / ugali.utils.projector.distanceModulusToDistance(distance_modulus))) # One choice of theory prior #half_light_radius_physical = ugali.analysis.kernel.halfLightRadius(stellar_mass) # kpc #half_light_radius = np.degrees(np.arcsin(half_light_radius_physical \ # / ugali.utils.projector.distanceModulusToDistance(distance_modulus))) if plot: pylab.figure() #pylab.scatter(lon, lat, c=distance_modulus, s=500 * half_light_radius) #pylab.colorbar() pylab.scatter(lon, lat, edgecolors='none') xmin, xmax = pylab.xlim() # Reverse azimuthal axis pylab.xlim([xmax, xmin]) pylab.title('Random Positions in Survey Footprint') pylab.xlabel('Longitude (deg)') pylab.ylabel('Latitude (deg)') pylab.figure() pylab.scatter(stellar_mass, ugali.utils.projector.distanceModulusToDistance(distance_modulus), c=(60. * half_light_radius), s=500 * half_light_radius, edgecolors='none') pylab.xscale('log') pylab.yscale('log') pylab.xlim([0.5 * range_stellar_mass[0], 2. * range_stellar_mass[1]]) pylab.colorbar() pylab.title('Half-light Radius (arcmin)') pylab.xlabel('Stellar Mass (arcmin)') pylab.ylabel('Distance (kpc)') return simulation_area, lon, lat, distance, stellar_mass, r_physical
def plot_model(self): param_names = ['a','b','c','d','e'] # settings pl.clf() pl.rc('text', usetex=True) pl.rc('font', **{'family': 'serif', 'serif': ['Computer Modern'], 'size': 20}) pl.rcParams['xtick.major.pad']='8' pl.rcParams['ytick.major.pad']='8' pl.xscale('log') pl.yscale('log') pl.xlabel('$\phi = Q/V_D$') pl.ylabel('$\mathcal{I}_{tmp}( \phi)$') pl.grid() pl.axis([0.00001,1,0.0001,0.1]) pl.subplots_adjust(bottom=0.15) pl.subplots_adjust(left=0.17) # generating points for functions plotting x_model = pow(10,pl.linspace(-6,0,1000)) y_model = self.model(x_model, *self.parameters) p_model, = pl.plot(x_model, y_model, ls='--', color='Red') p_model.set_label(self.latex) l_1 = pl.legend(loc=2, prop={'size':15}) ll = '' for i in range(self.n_parameters): ll = ll + param_names[i] + ' = ' + str("%.4f" % round(self.parameters[i],4)) + '$\pm$' + str("%.4f" % round(self.errors[i],4)) + ' ' l_2 = pl.legend([ll], loc=4, prop={'size':15}) pl.gca().add_artist(l_1) pl.plot(self.db.get_data().pi, self.db.get_data().imp,'.', color='Black',ms=10) pl.show()