def sp1_style( ax ): wf.ax_limits( sp1_lims ) pl.minorticks_on() wf.ax_labels( sp1_ax_labs ) # wf.major_ticks( ax, sp1_maj_loc ) # pl.legend( sp1_entries, loc=sp1_leg_loc ) # locate legend x,y from bottom left ax.yaxis.set_ticklabels([]) # y tick labels off
def run_setup(): mpl.rcParams.update(mpl.rcParamsDefault) mpl.rcParams['font.size'] = 26. mpl.rcParams['font.family'] = 'serif' #mpl.rcParams['font.family'] = 'serif' mpl.rcParams['font.serif'] = [ 'Times New Roman', 'Times','Palatino', 'Charter', 'serif'] mpl.rcParams['font.sans-serif'] = ['Helvetica'] mpl.rcParams['axes.labelsize'] = 24 mpl.rcParams['xtick.labelsize'] = 22. mpl.rcParams['ytick.labelsize'] = 22. mpl.rcParams['xtick.major.size']= 10. mpl.rcParams['xtick.minor.size']= 8. mpl.rcParams['ytick.major.size']= 10. mpl.rcParams['ytick.minor.size']= 8. mpl.rc('axes',**{'labelweight':'normal', 'linewidth':1}) mpl.rc('axes',**{'labelweight':'normal', 'linewidth':1}) mpl.rc('ytick',**{'major.pad':5, 'color':'k'}) mpl.rc('xtick',**{'major.pad':5, 'color':'k'}) #legend parameters too params = {'legend.fontsize': 24, 'legend.numpoints':1, 'legend.handletextpad':1 } plt.rcParams.update(params) plt.minorticks_on()
def plothistogram(): #plotting the histograms py.figure(2,(6.,3.5)) ax1 = py.subplot(2,1,1) py.plot(xgauss,num,'k',linewidth = 2,drawstyle = 'steps-pre') py.plot(xgauss,ygauss,'r--',linewidth = 2) py.setp(ax1.get_xticklabels(),visible = False) py.ylim(0,40) py.yticks([0.0,20,40]) py.xlim(-1.5,1.5) py.ylabel('N') py.xlabel('R$_{VI}$') py.minorticks_on() ax2 = py.subplot(2,1,2) py.plot(xgauss,resid,'k',linewidth = 2,drawstyle = 'steps-pre') py.plot(xgauss,zeroline,'k--',linewidth = 1) py.yticks([-10,0,10,20]) py.xlim(-2,2) py.xlabel('R$_{VI}$') py.ylabel('$\Delta$N') py.minorticks_on() py.subplots_adjust(hspace = 0) py.show()
def test_decomp(): nmax = 10. kmax = 10. dx = 0.1 * 2.**(-nmax) x = np.arange(-10., 10., dx) f = (2. / np.pi) * np.arctan(0.5 * x) nvals = np.arange(-nmax, nmax) kvals = np.arange(-kmax, kmax) Cnk = wavelet_decomp(x, f, nvals, kvals) fig, ax = plt.subplots() im = ax.matshow(Cnk, origin='lower', vmin=-1, vmax=1.5, extent=(-nmax, nmax, -kmax, kmax)) ax.xaxis.set_ticks_position('bottom') plt.minorticks_on() ax.grid(b=True, which='major', color='k', linestyle='-') ax.grid(b=True, which='minor', color='Grey', linestyle='--', dashes=(2, 5)) ax.set_ylabel(r"$k$", fontsize=18) ax.set_xlabel(r"$n$", fontsize=18) plt.colorbar(im) plt.savefig('Cnk_matrix.pdf') #plt.show() plt.clf() fr = wavelet_recov(Cnk, nvals, kvals, x) plt.plot(x, f, label='Original') plt.plot(x, fr, label='Recovered') plt.legend(loc='lower right') plt.savefig('recovered_function.pdf')
def view(self, show=True): """ View generated beam """ if self.generated_beam_data is None: raise RuntimeError("Beam pattern not generated yet. Run generate() first.") plt.figure(figsize=(8,4)) plt.subplot(121) tmin, tmax = self.generated_beam_theta[0], self.generated_beam_theta[-1] pmin, pmax = self.generated_beam_phi[0], self.generated_beam_phi[-1] plt.imshow(10**(self.generated_beam_data / 10), extent=(tmin, tmax, pmin, pmax), aspect='auto') plt.xlabel("Theta [deg]") plt.ylabel("Phi [deg]") #plt.colorbar(orientation='horizontal') plt.subplot(122) beam_slice = self.generated_beam_data[self.generated_beam_data.shape[0]/2] print self.generated_beam_phi.shape, beam_slice.shape plt.plot(self.generated_beam_theta, beam_slice, c='#333333') plt.xlabel("Theta [deg]") plt.ylabel("Normalized gain [dB]") plt.xlim(-91, 91) plt.ylim(-30, 3) plt.minorticks_on() plt.tight_layout() if show: plt.show()
def wavelengthScalePlot(out_dir, base_name, order): pl.figure('wavelength scale', facecolor='white') pl.cla() pl.title('wavelength scale, ' + base_name + ', order ' + str(order.orderNum), fontsize=14) pl.xlabel('column (pixels)') pl.ylabel('wavelength ($\AA$)') pl.minorticks_on() pl.grid(True) pl.xlim(0, 1023) pl.plot(order.gratingEqWaveScale, "k-", mfc='none', ms=3.0, linewidth=1, label='grating equation') if order.waveScale is not None: pl.plot(order.waveScale, "b-", mfc='none', ms=3.0, linewidth=1, label='sky lines') pl.legend(loc='best', prop={'size': 8}) fn = constructFileName(out_dir, base_name, order.orderNum, 'wavelength_scale.png') pl.savefig(fn) pl.close() return
def plot_coordinate(index, name, negate=False, label=None): ax = pl.subplot(3, 1, index) if negate: plot_primary_leg(name, mult=-1.0) plot_opposite_leg(name, mult=-1.0) else: plot_primary_leg(name) plot_opposite_leg(name) # TODO this next line isn't so great of an idea: if label == None: label = name.replace('_', ' ') pl.ylabel('%s (N-m)' % label) pl.legend() if toeoff_time != None: duration = cycle_end - cycle_start # 'pgc' is percent gait cycle if toeoff_time > primary_footstrike: toeoff_pgc = percent_duration_single( toeoff_time, primary_footstrike, duration + primary_footstrike) else: chunk1 = cycle_end - primary_footstrike chunk2 = toeoff_time - cycle_start toeoff_pgc = (chunk1 + chunk2) / duration * 100.0 pl.plot(toeoff_pgc * np.array([1, 1]), ax.get_ylim(), c=(0.5, 0.5, 0.5)) pl.xticks([0.0, 25.0, 50.0, 75.0, 100.0]) pl.minorticks_on() pl.grid(b=True, which='major', color='gray', linestyle='--') pl.grid(b=True, which='minor', color='gray', linestyle='--')
def plot_ACF(y_avg, n): n_lags = len(y_avg) // 2 y_avg = differencing(y_avg, n) results_acf = acf(y_avg, nlags=n_lags - 1) plt.subplot(2, 1, 1) plt.plot(range(n_lags), results_acf, '-*') plt.minorticks_on() plt.xlabel("lag") plt.axhline(y=0, c='green', ls='--') plt.axhline(y=0.2, c='orange', ls='--') plt.axhline(y=-0.2, c='orange', ls='--') plt.grid(True, which='both') plt.ylabel("value of ACF") plt.title("ACF on Fourier residual") results_pacf = pacf(y_avg, nlags=n_lags - 1, method='ols') plt.subplot(2, 1, 2) plt.plot(range(n_lags), results_pacf, '-*') plt.minorticks_on() plt.xlabel("lag") plt.axhline(y=0, c='green', ls='--') plt.axhline(y=0.2, c='orange', ls='--') plt.axhline(y=-0.2, c='orange', ls='--') plt.grid(True, which='both') plt.ylabel("value of PACF") plt.title("PACF on Fourier residual") plt.suptitle('ACF and PACF plots with differencing = {0}'.format(n)) plt.show()
def style_plot( convolved = True ): pl.xlim( x_min, x_max ) pl.xlabel( x_str ) pl.ylabel( y_str ) pl.minorticks_on() if convolved: pl.xlim( x_min_conv, x_max_conv )
def wavelengthScalePlot(out_dir, base_name, order): pl.figure('wavelength scale', facecolor='white') pl.cla() pl.title('wavelength scale, ' + base_name + ', order ' + str(order.flatOrder.orderNum), fontsize=14) pl.xlabel('column (pixels)') pl.ylabel('wavelength ($\AA$)') pl.minorticks_on() pl.grid(True) pl.xlim(0, 1023) pl.plot(order.flatOrder.gratingEqWaveScale, "k-", mfc='none', ms=3.0, linewidth=1, label='grating equation') if order.waveScale is not None: pl.plot(order.waveScale, "b-", mfc='none', ms=3.0, linewidth=1, label='sky lines') pl.legend(loc='best', prop={'size': 8}) fn = constructFileName(out_dir, base_name, order.flatOrder.orderNum, 'wavelength_scale.png') pl.savefig(fn) pl.close() return
def specrect_plot(outpath, base_name, order_num, before, after): pl.figure('spectral rectify', facecolor='white') pl.cla() pl.title('spectral rectify, ' + base_name + ', order ' + str(order_num), fontsize=14) pl.xlabel('column (pixels)') pl.ylabel('intensity (counts)') pl.minorticks_on() pl.grid(True) pl.xlim(0, 1023) pl.plot(before[10, :], "k-", mfc='none', ms=3.0, linewidth=1, label='before') pl.plot(after[10, :], "b-", mfc='none', ms=3.0, linewidth=1, label='after') pl.legend(loc='best', prop={'size': 8}) fn = constructFileName(outpath, base_name, order_num, 'specrect.png') pl.savefig(fn) pl.close() return
def plot_s11_logmag(filename, c0='#333333', label=None, ls='solid'): """ Plot S11 log mag """ colnames, data = read_s2p(filename) plt.plot(data[:, 0], data[:, 1], c=c0, label=label, ls=ls) plt.xlabel(colnames[0]) plt.ylabel(colnames[1]) plt.minorticks_on()
def test_decomp(): nmax = 10.; kmax = 10. dx = 0.1*2.**(-nmax) x = np.arange(-10.,10.,dx) f = (2./np.pi)*np.arctan(0.5*x) nvals = np.arange(-nmax,nmax) kvals = np.arange(-kmax,kmax) Cnk = wavelet_decomp(x,f,nvals,kvals) fig, ax = plt.subplots() im = ax.matshow(Cnk,origin='lower',vmin=-1,vmax=1.5,extent=(-nmax,nmax,-kmax,kmax)) ax.xaxis.set_ticks_position('bottom') plt.minorticks_on() ax.grid(b=True, which='major', color='k', linestyle='-') ax.grid(b=True, which='minor', color='Grey', linestyle='--',dashes=(2,5)) ax.set_ylabel(r"$k$",fontsize=18) ax.set_xlabel(r"$n$",fontsize=18) plt.colorbar(im) plt.savefig('Cnk_matrix.pdf') #plt.show() plt.clf() fr = wavelet_recov(Cnk,nvals,kvals,x) plt.plot(x,f,label='Original') plt.plot(x,fr,label='Recovered') plt.legend(loc='lower right') plt.savefig('recovered_function.pdf')
def plot_s21_logmag(filename, c0='#333333', label=None, atten=0): """ Plot S11 log mag """ colnames, data = read_s2p(filename) plt.plot(data[:, 0], data[:, 3] + atten, c=c0, label=label) plt.xlabel(colnames[0]) plt.ylabel(colnames[1]) plt.minorticks_on()
def tracePlot(outpath, base_name, order_num, raw, fit, mask): pl.figure("Trace Plot", figsize=(6, 5), facecolor='white') pl.title('trace, ' + base_name + ", order " + str(order_num), fontsize=14) pl.xlabel('column (pixels)') pl.ylabel('row (pixels)') # yrange = offraw.max() - offraw.min() x = np.arange(raw.shape[0]) pl.plot(x[mask], raw[mask], "ko", mfc="none", ms=1.0, linewidth=1, label="derived") pl.plot(x, fit, "k-", mfc="none", ms=1.0, linewidth=1, label="fit") pl.plot(x[np.logical_not(mask)], raw[np.logical_not(mask)], "ro", mfc="red", mec="red", ms=2.0, linewidth=2, label="ignored") rms = np.sqrt(np.mean(np.square(raw - fit))) pl.annotate('RMS residual = ' + "{:.3f}".format(rms), (0.3, 0.8), xycoords="figure fraction") pl.minorticks_on() pl.grid(True) pl.legend(loc='best', prop={'size': 8}) fn = constructFileName(outpath, base_name, order_num, 'trace.png') pl.savefig(fn) pl.close() log_fn(fn) return
def single_plot_paras(fontsize=15, i_test=0, numpoints=1): """parameters for a single plot""" if i_test == 1: x = numpy.linspace(0, 1, 30) y = numpy.sin(x) pylab.figure() pylab.plot(x, y, '*') pylab.legend([ 'test', ]) pylab.xlabel('x label') pylab.ylabel('y label') pylab.title('test plot') pylab.rcParams['legend.numpoints'] = numpoints pylab.rcParams.update({'font.size': fontsize}) pylab.grid('on') pylab.minorticks_on() pylab.tick_params(which='major', labelsize=fontsize, width=2, length=10, color='black') pylab.tick_params(which='minor', width=1, length=5) pylab.tight_layout() if i_test == 1: pylab.show()
def view_thetaphi(self, show=True): """ View generated beam, in theta-phi coordinates """ self._check_generated() plt.figure(figsize=(8,4)) plt.subplot(121) tmin, tmax = self.generated_beam_theta[0], self.generated_beam_theta[-1] pmin, pmax = self.generated_beam_phi[0], self.generated_beam_phi[-1] plt.imshow(10**(self.generated_beam_data / 10), extent=(tmin, tmax, pmin, pmax), aspect='auto') plt.xlabel("Theta [deg]") plt.ylabel("Phi [deg]") #plt.colorbar(orientation='horizontal') plt.subplot(122) beam_slice = self.generated_beam_data[self.generated_beam_data.shape[0]/2] print self.generated_beam_phi.shape, beam_slice.shape plt.plot(self.generated_beam_theta, beam_slice, c='#333333') plt.xlabel("Theta [deg]") plt.ylabel("Normalized gain [dB]") plt.xlim(-91, 91) plt.ylim(-30, 3) plt.minorticks_on() plt.tight_layout() if show: plt.show()
def initiatePlotting(self): self.LINES = [] self.line, = plot([0], [0], marker=".") grid(b=True, which='major', color='0', linestyle='-', alpha=0.3) grid(b=True, which='minor', color='0', linestyle='-', alpha=0.05) minorticks_on() ion()
def my_plot(l1,l2,ll1,ll2,li1,li2,xx,n): fig = plt.figure(num=None, figsize=(8, 8), dpi=80, facecolor='w', edgecolor='k') ## plt.subplot(1,2,1) ## plt.plot(l1) ## plt.plot(l2) ## plt.grid(1,which='both') ## plt.minorticks_on() ## plt.axvline(x=l2_index,c='g',ls='--') ## plt.axvline(x=l1_index,c='r',ls='--') ## plt.axvline(x=l1_index_rise,c='b',ls='--') ## ## plt.subplot(1,2,2) plt.plot(xx,ll1,'.-') plt.plot(xx,ll2,'.-') xx = np.linspace(1,n,n) plt.plot(xx,li1,'*-') plt.plot(xx,li2,'*-') plt.grid(1,which='both') plt.minorticks_on() plt.suptitle('file name : {0}, {1}, time : {2}, ratio : {3} / {4}'.format(read_name,tt1,l2_index,len(ll1),n)) plt.savefig('D:/OneDrive - Tata Insights and Quants, A division of Tata Industries/Confidential/Projects/Steel/LD2 BDS/prelim_analysis/plots/second iteration/extracted_true/{0}_{1}_time_{2}.png'.format(read_name,tt1,l2_index)) plt.close() ## plt.show() ## pass
def prettifyPlot(xlabel,ylabel): plt.xlabel(xlabel,fontsize=30) plt.ylabel(ylabel,fontsize=30) plt.tick_params(axis='both',labelsize=20) plt.minorticks_on() plt.tick_params(which='both', width=2,direction='in') #this has to be a separate line because width can't be set when using which='minor' plt.tick_params(which='major', length=8, direction='in') #If you want tick marks on the opposite side also, add right=True plt.tick_params(which='minor', length=4)
def sp1_style( ax ): pl.xlim( sp1_x_lim ) pl.ylim( sp1_y_lim ) pl.minorticks_on() ax.xaxis.set_major_locator( mpl.ticker.MultipleLocator( sp1_maj_loc[0] ) ) ax.yaxis.set_major_locator( mpl.ticker.MultipleLocator( sp1_maj_loc[1] ) ) ax.xaxis.set_ticklabels( sp1_x_tick_labs ) # x tick labels mpl.rc( 'legend', numpoints=1, handletextpad=0.5, borderpad=1 )
def spectrumPlot2(outpath, base_name, title, order_num, y_units, cont1, cont2, wave, wave_note='unknown'): """ Borrow from the code in NSDRP: products.py: to compare flux and noise """ if const.upgrade: endPix = 2048 - 40 else: endPix = 1024 - 20 pl.figure(title, facecolor='white') pl.clf() pl.title(title + ', ' + base_name + ", order " + str(order_num), fontsize=12) pl.xlabel('wavelength ($\AA$) (' + wave_note + ')') if len(y_units) > 0: pl.ylabel(title + '(' + y_units + ')') else: pl.ylabel(title) pl.grid(True) pl.plot(wave[:endPix], cont1[:endPix], "k-", wave[:endPix], cont2[:endPix], "r-", mfc="none", ms=3.0, linewidth=1) ymin, ymax = pl.ylim() pl.plot(wave, cont1, "k-", wave, cont2, "r-", mfc="none", ms=3.0, linewidth=1) pl.ylim(ymin, ymax) pl.minorticks_on() # axes = pl.gca() #axes.set_ylim(0, 300) fn = constructFileName(outpath, base_name, order_num, title + '.png') savePreviewPlot(fn) log_fn(fn) return
def draw_results(self, T, X): pylab.close() pylab.plot(X, T, color='r') pylab.grid(which='major', color='silver', linestyle="-", linewidth=1) pylab.minorticks_on() pylab.title('Tube temperature') pylab.ylabel('T, K', rotation=0) pylab.xlabel('Len, cm') pylab.show()
def show_grid(): minorticks_on() grid(which='major', linestyle='-') grid(which='minor', linestyle='--') xticks(fontsize=12, fontweight='bold', family='Times New Roman') yticks(fontsize=12, fontweight='bold', family='Times New Roman', rotation=90)
def plot_gplane(d, title='', cbar_label="DM [pc cm$^{-3}$]"): plt.imshow(d.T[::-1, ::-1], extent=(-180, 180, -90, 90), cmap='magma') plt.ylim(-60, 60) cb = plt.colorbar() cb.set_label(cbar_label) plt.title(title) plt.xticks([-180, -120, -60, 0, 60, 120, 180]) plt.yticks([-60, -30, 0, 30, 60]) plt.ylabel("gb [deg]") plt.minorticks_on()
def axes_format( subplot_number ): ax = pl.gca() ax.set_xlabel( x_axis_label ) ax.set_ylabel( y_axis_label ) ax.xaxis.major.formatter._useMathText = True ax.yaxis.major.formatter._useMathText = True majorLocator = mpl.ticker.MultipleLocator( major_locators[ subplot_number - 1 ] ) ax.xaxis.set_major_locator( majorLocator ) ax.yaxis.set_major_locator( majorLocator ) pl.minorticks_on() # minor ticks on
def result_plot(history): # list all data in history print(history.history.keys()) # summarize history for loss plt.plot(history.history['loss']) plt.title('model loss') plt.ylabel('loss') plt.xlabel('epoch') plt.minorticks_on() plt.grid(1, 'both') plt.show()
def plot_antenna_array(antpos): """ Plot an antenna array (2D X-Y positions). """ antpos = np.array(antpos) plt.plot(antpos[:,0], antpos[:, 1], 'o', c='#333333') plt.xlabel('x-pos [m]') plt.ylabel('y-pos [m]') #plt.xlim(np.min(antpos[:, 0]) - 2, np.max(antpos[:, 0]) + 2) #plt.ylim(np.min(antpos[:, 1]) - 2, np.max(antpos[:, 1]) + 2) plt.minorticks_on() plt.savefig("figures/antenna-positions.pdf") plt.show()
def plot_antenna_array(antpos): """ Plot an antenna array (2D X-Y positions). """ antpos = np.array(antpos) plt.plot(antpos[:, 0], antpos[:, 1], 'o', c='#333333') plt.xlabel('x-pos [m]') plt.ylabel('y-pos [m]') #plt.xlim(np.min(antpos[:, 0]) - 2, np.max(antpos[:, 0]) + 2) #plt.ylim(np.min(antpos[:, 1]) - 2, np.max(antpos[:, 1]) + 2) plt.minorticks_on() plt.savefig("figures/antenna-positions.pdf") plt.show()
def format_axes( subplot_number ): ax = pl.gca() ax.set_xlabel( x0_lab ) ax.set_ylabel( y0_lab ) ax.xaxis.major.formatter._useMathText = True ax.yaxis.major.formatter._useMathText = True majorLocator = mpl.ticker.MultipleLocator( major_locators[ subplot_number ] ) ax.xaxis.set_major_locator( majorLocator ) ax.yaxis.set_major_locator( majorLocator ) pl.minorticks_on() # minor ticks on pl.xlim( x_lims[ subplot_number ] ) #define chart limits pl.ylim( y_lims[ subplot_number ] )
def plot_multiple_1d( data, col_0, col_n, color='', style='', shift='' ): columns = data.shape[1] x = data[ :, 0 ] if len( shift ) == 2 : shift_value = shift[ 0 ] shift_center = shift[ 1 ] x = x + ( shift_center - shift_value ) for i in range( col_0, col_n ): pl.plot( x, data[ :, i ], color = color, marker = style ) pl.minorticks_on() pl.show()
def plotabsxsec(axs1,axs2,freq,pres,absspec, abswhich=None,doboth=1, meandelta=0, facdiff=0, newfig=True,save=False, title='Spectroscopy HITRAN vs. Toolbox: ', casename='H-vs-TB', outdir='~/projects/MicrowavePropagationToolbox/study/Validation/basics/figures/'): ''' ''' sps1,sps2 = prep2to1plot() col=['b','g','r','c','m','y','k'] if abswhich is None: abswhich=N.arange(axs1.shape[1]) for i in abswhich: if ((axs1[0,i,:,:]+axs2[0,i,:,:]).max()!=0.): p.figure() ax1=p.subplot(sps1) ax2=p.subplot(sps2,sharex=ax1) for j in N.arange(axs2.shape[-1]): if meandelta: ax2.plot(freq*1e-9,(axs2[0,i,:,j]-axs1[0,i,:,j])/(axs2[0,i,:,j]+axs1[0,i,:,j])*2e2, col[j%N.size(col)]+'-',linewidth=2) elif facdiff: # ax2.semilogy(freq*1e-9,N.maximum(axs1[0,i,:,j]/axs2[0,i,:,j],axs2[0,i,:,j]/axs1[0,i,:,j])*1e2-1e2, # col[j%N.size(col)]+'-',linewidth=2) ax2.semilogy(freq*1e-9,N.maximum(axs1[0,i,:,axs2.shape[-1]-j-1]/axs2[0,i,:,axs2.shape[-1]-j-1],axs2[0,i,:,axs2.shape[-1]-j-1]/axs1[0,i,:,axs2.shape[-1]-j-1])-1., col[(axs2.shape[-1]-j-1)%N.size(col)]+'-',linewidth=2) else: ax2.plot(freq*1e-9,axs2[0,i,:,j]/axs1[0,i,:,j]*1e2-1e2, col[j%N.size(col)]+'-',linewidth=2) ax1.semilogy(freq*1e-9,axs2[0,i,:,j], col[j%N.size(col)]+'-',linewidth=2,label='%.1ePa' %pres[j]) if doboth: ax1.semilogy(freq*1e-9,axs1[0,i,:,j],col[j%N.size(col)]+'--',linewidth=2) ax1.set_xlabel('Frequency [GHz]') ax1.set_ylabel('absolute cross section [m2]') if facdiff: ax2.set_ylabel('factor difference [-]') else: ax2.set_ylabel('relative difference [%]') ax1.legend(loc=0) p.minorticks_on() p.title('%s %s' %(title,absspec[i])) p.tight_layout() if save: p.savefig('%sAbsXsec_%s_%s_xsec-log_drel-lin.png' %(os.path.expanduser(outdir),casename,absspec[i])) else: print('No abs xs !=0 (no lines? vmr=0?) for %s' %absspec[i]) p.show() return ax1,ax2
def specrect_plot2(outpath, base_name, order_num, before, after, eta=None, arc=None): if const.upgrade: endPix = 2048 else: endPix = 1024 pl.figure('spectral rectify', facecolor='white') pl.cla() pl.title('spectral rectify, ' + base_name + ', order ' + str(order_num), fontsize=14) pl.xlabel('column (pixels)') pl.ylabel('intensity (counts)') pl.minorticks_on() pl.grid(True) pl.xlim(0, endPix - 1) pl.plot(before[10, :], "k-", mfc='none', ms=3.0, linewidth=1, label='before', alpha=0.5) pl.plot(after[10, :], "b-", mfc='none', ms=3.0, linewidth=0.7, label='after', alpha=0.5) pl.legend(loc='best', prop={'size': 8}) pl.minorticks_on() fn = constructFileName(outpath, base_name, order_num, 'specrectplot.png') pl.savefig(fn) #pl.show() pl.close() return
def make_plot(self): '''Plot the mass detection limits.''' # Plot BTsettl curve plt.plot(self.projsep, self.Spiegmasslim, 'b-', lw=2, label='Spiegel & Burrows') plt.plot(self.projsep, self.BTmasslim, 'r-', lw=2, label=' BT-Settl') plt.xlabel('Projected Separation (AU)') plt.ylabel(' Planet Mass (M$_{\mathrm{Jup}})$') plt.minorticks_on() plt.legend(loc='upper right') plt.savefig('plots/'+self.title+'.png') plt.show()
def plot_lombscargle(self): from scipy.signal import lombscargle n = 2000 f = np.linspace(2. * np.pi / 20, 2. * np.pi / 0.1, n) pgram = lombscargle(self.t, self.m, f) period = 1. / (f / (2. * np.pi)) plt.plot(period, np.sqrt(4 * (pgram / n)), 'r') plt.xlabel('period [days]') plt.ylabel('FAP') plt.xticks(np.arange(20)) plt.xlim(0.1, 20) plt.minorticks_on() plt.grid()
def plot_raw(y, time): n = 60 plt.subplot(2, 1, 1) plt.plot(time, y, '.-') plt.plot(time, pd.rolling_mean(y, n), '.-', color='purple') plt.minorticks_on() plt.legend(['raw', 'MA 60']) plt.grid(b=True, which='both') plt.subplot(2, 1, 2) plt.plot(time, np.log(y), '.-', color='black') plt.plot(time, pd.rolling_mean(np.log(y), n), '.-', color='green') plt.minorticks_on() plt.legend(['log', 'MA 60']) plt.grid(b=True, which='both') plt.show()
def plot_monthly(y_avg, time_avg): n = 6 plt.subplot(2, 1, 1) plt.plot(time_avg, y_avg, '.-') plt.plot(time_avg, pd.rolling_mean(y_avg, n), '.-', color='purple') plt.minorticks_on() plt.legend(['raw monthly', 'MA 6']) plt.grid(b=True, which='both') plt.subplot(2, 1, 2) plt.plot(time_avg, np.log(y_avg), '.-', color='black') plt.plot(time_avg, pd.rolling_mean(np.log(y_avg), n), '.-', color='green') plt.minorticks_on() plt.legend(['log monthly', 'MA 6']) plt.grid(b=True, which='both') plt.show()
def plot_psd(self, show=False, save=False): from psd import ppsd t, m = self.t, self.m - np.mean(self.m) n = len(t) t_padded = np.zeros(8 * n) t_padded[:n] = t t_padded[n:] = np.linspace(max(t), 8 * max(t), 7 * n) m_padded = np.zeros(8 * n) m_padded[:n] = m filename = config.datapath + '/psd/%s.psd' % self.starid try: px, f = np.loadtxt(filename, unpack=True) except IOError: # perform a power spectrum analysis px, f = ppsd(t_padded, m_padded, lower=1. / 20, upper=1. / 0.1) np.savetxt(filename, np.column_stack((px, f))) px = np.sqrt(px) i = np.argmax(px) period1 = 1. / f[i] t_window = np.linspace(0, 8 * max(t), 8 * max(t) * 24) m_window = np.zeros(len(t_window)) for tt in t: i = np.argmin(abs(t_window - tt)) m_window[i] = max(abs(m)) / 2 p_win = abs(np.fft.rfft(m_window)) p_win /= p_win.size f_win = np.fft.fftfreq(t_window.size, 1.0 / 24)[:p_win.size] plt.axvline(x=period1, color='green', alpha=0.5) plt.plot(1. / f[1:], px[1:] * 1000.0, 'r') plt.plot(1. / f_win[1:], p_win[1:] * 1000.0, 'k') plt.axhline(np.std(px) * 5000.0, linestyle='--', color='b') plt.xticks(np.arange(20)) plt.xlim(0.1, 20) plt.xlabel('period [days]') plt.ylabel('semi-amplitude [mmag]') plt.minorticks_on() plt.grid() if show: plt.show() elif save: plt.savefig(config.plotpath + '%s_psd.pdf' % self.starid)
def multiSpectrumPlot(outpath, base_name, order, y_units, cont, sky, noise, wave): if const.upgrade: endPix = 2048 - 40 else: endPix = 1024 - 20 title = 'spectrum' pl.figure(title, facecolor='white') pl.clf() pl.title(title + ', ' + base_name + ", order " + str(order), fontsize=12) pl.xlabel('Wavelength ($\AA$)') pl.ylabel(title + '(' + y_units + ')') pl.grid(True) pl.plot(wave[:endPix], cont[:endPix], "k-", mfc="none", ms=3.0, linewidth=1, label='object') pl.plot(wave[:endPix], sky[:endPix], "b-", mfc="none", ms=3.0, linewidth=1, label='sky') pl.plot(wave[:endPix], noise[:endPix], "r-", mfc="none", ms=3.0, linewidth=1, label='noise (1 sigma)') pl.legend(loc='best', prop={'size': 8}) pl.minorticks_on() fn = constructFileName(outpath, base_name, order, 'spectra.png') savePreviewPlot(fn) log_fn(fn) pl.close() return
def plot_lightcurve(self, show=False, save=False): """ plot the lightcurve for a given star """ mean = np.mean(self.m) std = np.std(self.m) plt.hlines(mean, min(self.t), max(self.t), linestyle='--') plt.ylim(mean + std * 3, mean - std * 3) plt.xlim(min(self.t), max(self.t)) plt.grid() plt.title(self.starid + ' = star #' + str(self['tab'])) plt.xlabel('days') plt.ylabel('mag') plt.scatter(self.t, self.m, edgecolor='none') plt.plot(self.t, self.m, 'gray') plt.minorticks_on()
def plotSpline(self, x, y): """ Plot the spline interpolation of the given x and y values. """ # compute fit yFit = [] for v in x: yFit.append(self.interpolate(v)) # plot results plt.plot (x, y, 'bo', label='Original') plt.plot (x, yFit, 'r-', label='Spline fit') plt.minorticks_on() plt.legend() plt.xlabel('x') plt.ylabel('y') plt.show()
def twoDimNoiseOrderPlot(outpath, base_name, title, base_filename, order_num, data, x_scale, wave_note='unknown'): """ Produces a generic 2-d image plot. Arguments: output: Directory path of root products directory. base_name: Base name of object frame. title: Title of plot, e.g. rectified order image. base_filename: order_num: data: x_scale: """ pl.figure('2d order image', facecolor='white', figsize=(8, 5)) pl.cla() pl.title(title + ', ' + base_name + ", order " + str(order_num), fontsize=14) pl.xlabel('wavelength($\AA$) (' + wave_note + ')', fontsize=12) pl.ylabel('row (pixel)', fontsize=12) pl.imshow(exposure.equalize_hist(data), origin='lower', extent=[x_scale[0], x_scale[-1], 0, data.shape[0]], aspect='auto') # pl.colorbar() # pl.set_cmap('jet') pl.set_cmap('gray') # pl.set_cmap('Blues_r') pl.minorticks_on() fn = constructFileName(outpath, base_name, order_num, base_filename) savePreviewPlot(fn) log_fn(fn) pl.close() return
def plot_s2p(filename, save_fig=True, show_fig=True, s11=True, c0='#cc0000', c1='#333333'): """ Plot S2P file """ colnames, data = read_s2p(filename) if len(colnames) != 9: print "Unknown S2P format!" else: #plt.figure("S2P", figsize=(8,8)) plt.suptitle(filename) if s11: plt.subplot(2, 1, 1) else: plt.subplot(2, 2, 1) plt.plot(data[:, 0], data[:, 1], c=c0) plt.xlabel(colnames[0]) plt.ylabel(colnames[1]) plt.minorticks_on() if s11: plt.subplot(2, 1, 2) else: plt.subplot(2, 2, 3) plt.plot(data[:, 0], data[:, 2], c=c1) plt.xlabel(colnames[0]) plt.ylabel(colnames[2]) plt.minorticks_on() if not s11: plt.subplot(2, 2, 2) plt.plot(data[:, 0], data[:, 3], c=c0) plt.xlabel(colnames[0]) plt.ylabel(colnames[1]) plt.minorticks_on() plt.subplot(2, 2, 4) plt.plot(data[:, 0], data[:, 4], c=c1) plt.xlabel(colnames[0]) plt.ylabel(colnames[2]) plt.minorticks_on() if save_fig: plt.savefig(filename + '.pdf') if show_fig: plt.show() else: pass
def tracePlot(outpath, base_name, order_num, raw, fit, mask): pl.figure("Trace Plot", figsize=(6, 5), facecolor='white') pl.title('trace, ' + base_name + ", order " + str(order_num), fontsize=14) pl.xlabel('column (pixels)') pl.ylabel('row (pixels)') # yrange = offraw.max() - offraw.min() x = np.arange(raw.shape[0]) pl.plot(x[mask], raw[mask], "ko", mfc="none", ms=1.0, linewidth=1, label="derived") pl.plot(x, fit, "k-", mfc="none", ms=1.0, linewidth=1, label="fit") pl.plot(x[np.logical_not(mask)], raw[np.logical_not(mask)], "ro", mfc="red", mec="red", ms=2.0, linewidth=2, label="ignored") rms = np.sqrt(np.mean(np.square(raw - fit))) pl.annotate('RMS residual = ' + "{:.3f}".format(rms), (0.3, 0.8), xycoords="figure fraction") pl.minorticks_on() pl.grid(True) pl.legend(loc='best', prop={'size': 8}) fn = constructFileName(outpath, base_name, order_num, 'trace.png') savePreviewPlot(fn) pl.close() log_fn(fn) return
def plot_toa_reflectance(self, roi=[400], hold="off", show=True): xdata = scipy.linspace(0, self.num_bands, self.num_bands) for i in range(len(roi)): pylab.errorbar( self.bands[self.sensor_name], self.reflectance[roi[i], :], yerr=self.reflectance_std[roi[i], :] ) # pylab.scatter(self.bands[self.sensor_name], self.reflectance[roi[i], :]) pylab.minorticks_on() pylab.xlabel("Wavelength (nm)") pylab.ylabel("TOA Reflectance (sr^{-1})") pylab.ylim([0, 1]) pylab.title(self.sensor_name) if hold == "off" and show: pylab.show() if show: pylab.show()
def plot_setticks(x=True, y=True): pl.minorticks_on() ax = pl.gca() if x: ax.xaxis.set_major_locator(pl.AutoLocator()) x_major = ax.xaxis.get_majorticklocs() dx_minor = (x_major[-1] - x_major[0]) / (len(x_major) - 1) / 5.0 ax.xaxis.set_minor_locator(pl.MultipleLocator(dx_minor)) else: pl.minorticks_off() if y: ax.yaxis.set_major_locator(pl.AutoLocator()) y_major = ax.yaxis.get_majorticklocs() dy_minor = (y_major[-1] - y_major[0]) / (len(y_major) - 1) / 5.0 ax.yaxis.set_minor_locator(pl.MultipleLocator(dy_minor)) else: pl.minorticks_off()
def timestructure_dataset(ds, calname="p_filt_value_dc"): pulse_timing.choose_laser_dataset(ds, "not_laser") cal = ds.calibration[calname] # energy = ds.p_energy[ds.cuts.good()] # cmap = plt.get_cmap() # cmap = [cmap(i/float(len(cal.elements))) for i in xrange(len(cal.elements))] for line_name in ["CoKAlpha", "FeKAlpha", "MnKAlpha"]: try: plt.figure() low,high = mass.energy_calibration.STANDARD_FEATURES[line_name]*np.array([0.995, 1.005]) use = np.logical_and(np.logical_and(ds.cuts.good(), ds.p_energy>low), ds.p_energy<high) plt.plot(ds.p_timestamp[use], ds.p_energy[use],'.') plt.xlabel("frame timestamp (s)") plt.ylabel("p_energy") pfit = np.polyfit(ds.p_timestamp[use], ds.p_energy[use],1) plt.title("chan %d, %s, not_laser pulses selected\nslope= %0.2f eV/hr"%(ds.channum, line_name, pfit[0]*3600)) plt.minorticks_on() plt.grid("on") plt.grid("on", which="minor") except: pass
def plot_toa_reflectance(self, roi=[2000], hold='off', show=True): xdata = scipy.linspace(0, self.num_bands, self.num_bands) for i in range(len(roi)): #pylab.errorbar(self.bands[self.sensor_name], self.reflectance[roi[i], :], # yerr=self.reflectance_std[roi[i], :]) xdata = self.bands[self.sensor_name] for j in range(0, len(self.bands[self.sensor_name])): xdata[j] = str(xdata[j]).strip('abcdefghijklmnopqrstuvwxyz') pylab.plot(xdata, self.reflectance[roi[i], :], 'o') pylab.minorticks_on() pylab.xlabel('Wavelength (nm)') pylab.ylabel('TOA Reflectance (sr^{-1})') pylab.ylim([0, 1]) pylab.title(self.sensor_name) if hold == 'off' and show: pylab.show() if show: pylab.show()
f5 = np.loadtxt(five_filename) #f6 = np.loadtxt(six_filename) #f7 = np.loadtxt(seven_filename) #f8 = np.loadtxt(eight_filename) pl.figure() pl.plot(f1[:,1],f1[:,3],'r-',label='L1',lw=1.5) #pl.plot(f2[:,1],f2[:,3],'b:',label='L2',lw=2) #pl.plot(f3[:,1],f3[:,3],'g--',label='L3',lw=2) #pl.plot(f4[:,1],f4[:,3],'m-.',label='L4',lw=2) pl.ylim([0,9]) pl.xlim([210,70]) #pl.title('rms source comparison') pl.xlabel('$\\nu_{\\rm obs}\; \\rm{[MHz]}$') pl.ylabel('$<\delta T_{\\rm b}>^{1/2}\; \\rm{[mK]}$') pl.minorticks_on() leg = pl.legend(loc='upper left',prop={'size':11}) leg.draw_frame(False) pl.savefig('./eps/dTrms_244_rsd_lc_sources.eps') pl.savefig('./png/dTrms_244_rsd_lc_sources.png') pl.clf() pl.plot(f1[:,1],f1[:,3],'r-',lw=1.5,label='L1') #pl.plot(f2[:,1],f2[:,7],'b:',lw=2,label='L2') #pl.plot(f3[:,1],f3[:,7],'g--',lw=2,label='L3') #pl.plot(f4[:,1],f4[:,7],'m-.',lw=2,label='L4') #pl.plot(f1[:,1],f1[:,7],'r',label='no LMACHs') #pl.plot(f2[:,1],f2[:,7],'b',label='supp LMACHs') #pl.plot(f3[:,1],f3[:,7],'g',label='psupp LMACHs') #pl.plot(f4[:,1],f4[:,7],'m',label='gsupp LMACHs') pl.ylim([0,5])
def eels_style( ax ): pl.xlim( eels_x ) pl.ylim( eels_y ) pl.minorticks_on() ax.xaxis.set_major_locator( mpl.ticker.MultipleLocator( eels_x_maj_loc ) ) ax.yaxis.set_ticklabels([]) # y tick labels off
mpl.rcParams['ytick.major.size']= 15. mpl.rcParams['ytick.minor.size']= 10. #mpl.rcParams['figure.autolayout']= True #fontsize=26 #mpl.rc('axes', titlesize=fontsize) #mpl.rc('axes', labelsize=fontsize) #mpl.rc('xtick', labelsize=fontsize) #mpl.rc('ytick', labelsize=fontsize) #mpl.rc('font', size=fontsize, family='serif', serif='Utopia', # style='normal', variant='normal', # stretch='normal', weight='normal') #mpl.rc('font',**{'family':'serif','serif':[ 'Times New Roman', 'Times', 'serif'], # 'sans-serif':['Helvetica'], 'size':19, # 'weight':'normal'}) mpl.rc('axes',**{'labelweight':'normal', 'linewidth':1}) mpl.rc('axes',**{'labelweight':'normal', 'linewidth':1}) mpl.rc('ytick',**{'major.pad':5, 'color':'k'}) mpl.rc('xtick',**{'major.pad':5, 'color':'k'}) params = {'legend.fontsize': 24, 'legend.linewidth': 1, 'legend.numpoints':1, 'legend.handletextpad':1 } plt.rcParams.update(params) plt.minorticks_on()
"""Plots a histogram showing positional residuals between IPHAS and UCAC4.""" import pylab as p from astropy.table import Table t = Table.read('iphas-x-ucac4.fits') p.figure() p.hist(t['Separation']*3600., range=[0.0, 0.5], bins=50, lw=1.0, color='#dddddd') p.minorticks_on() p.xlim([0,0.5]) p.xlabel('Astrometric residuals against UCAC4 [arcsec]', fontsize=9) p.ylabel('Stars', fontsize=9) p.tight_layout(pad=0.5) p.savefig('astrometry.pdf')
import xray, numpy, pylab # put materials and thickness in microns in m dictionary m={} m['Air']=2e5 m['Kapton']=25*8 m['Al']=20 m['Water']=120 m['Fe']=0.4 e_pulse = {"XOSpolycapillary_1":3.2,"XOSpolycapillary_2":4.125} pylab.figure() for optic_name, optic in xray.optics.iteritems(): energies = numpy.linspace(optic.energies[0], optic.energies[-1],1000) flux = xray.source_optic_materials_absorber(e_pulse[optic_name], optic_name, m, energies=energies, absorber_length_um=2) pylab.plot(energies,flux,label="%s, %d mJ"%(optic_name, e_pulse[optic_name])) pylab.xlabel('energy (eV)') pylab.ylabel('flux (arb)') pylab.legend() pylab.xlim(3000,15000) pylab.title(repr(m)) pylab.minorticks_on() pylab.grid()
def rthetaz_pop(): # Creates a 1.e3 x 1.e3 x 1.e3 array of random numbers randa=scipy.random.random_sample(size=(10000,3)) # IAU Galactic constants R0 = 8500.0 V0 = 220.0 # R is the radius, phi is the azimuth # Populate the cylinder phi = -math.pi + 2*math.pi*randa[:,0] R = 25000.*randa[:,1] z = -100. + 200*randa[:,2] # Transform the the (R, phi, z) into cartesian. To be consistent with l,b standards: # coordinates (X,Y,Z), centred on the Galactic Centre. +Y should point towards the Sun # +X should point in the direction of rotation, and # +Z should point above the plane (positive b, North Galactic Pole). # Defined this way, phi is zero at the Sun-Centre line and increases in the direction of Galactic rotation. x = R * np.sin(phi) y = R * np.cos(phi) z = z print "Min x: %.2f Max x: %.2f" % (min(x),max(x)) print "Min y: %.2f Max y: %.2f" % (min(y),max(y)) print "Min z: %.2f Max z: %.2f" % (min(z),max(z)) # Make a spiral of the model used for velocity field X1 = np.arange(-10000, 10000, 100) Y1 = np.arange(-10000, 10000, 100) X1, Y1 = np.meshgrid(X1, Y1) R1 =np.sqrt(X1**2 + Y1**2) Z1 = 1/np.tan(math.pi/2) * R1 # To Transform to the Galactic positions Y is along the Sun-GC line increasing away from the GC yprime=R0-1.0*y # Shift to the position of the Sun d = np.sqrt(yprime**2 + x**2 + z**2) lat = np.degrees(np.arcsin(z/d)) lon = np.degrees(np.arctan2(x,yprime)) for i in range(len(R)): if R[i] >= R0 * abs(np.sin(np.radians(lon[i]))) -10. and R[i] <= R0 * abs(np.sin(np.radians(lon[i]))) +10.0: print " %.2f %.2f %.2f %.2f %.2f" % (R[i], lon[i], d[i], x[i],y[i]) print lon[i],np.degrees(phi[i]) # Get the LSR velocity # NOTE phi is in radians whereas lon, and lat are in degrees vel = vlsr(R,z,d,lon,lat,phi) # Standard Galactic rotation #vel = vnoncirc(R,z,d,lon,lat,phi) #vel = vel2(R,z,d,lon,lat,phi) # Burton & Liszt (1978) tilted disk # Plot the distribution of points on a 3d plot fig = pylab.figure(2) pylab.clf() ax = Axes3D(fig) ax.scatter(x,y,z,marker='o',s=40, c=vel) surf = ax.plot_surface(X1, Y1, Z1,linewidth=0, antialiased=False) ax.set_xlabel('X (pc)') ax.set_ylabel('Y (pc)') ax.set_zlabel('Z (pc)') # Plot the x, y disk pylab.figure(1) pylab.clf() CS=pylab.scatter(x,y,s=20,c=vel) pylab.clim(-250,250) pylab.set_cmap('jet') CB=pylab.colorbar(CS) pylab.xlim(-25000,25000) pylab.ylim(-25000,25000) #pylab.contour(x,y,xi) pylab.xlabel("X (pc)") pylab.minorticks_on() pylab.ylabel("Y (pc)") pylab.savefig("sim_xyv.pdf") # Plot the l,b,v clouds pylab.figure(2) pylab.clf() CS=pylab.scatter(lon,lat,s=40,c=vel) pylab.clim(-250,250) pylab.set_cmap('jet') CB=pylab.colorbar(CS) pylab.xlim(180,-180) pylab.ylim(-5,5) pylab.xlabel("GALACTIC Longitude (deg)") pylab.ylabel("GALACTIC Latitude (deg)") pylab.savefig("sim_lb.pdf") return lon,lat,vel
def conc_style( ax ): pl.ylim( conc_y ) pl.minorticks_on() ax.xaxis.set_major_locator( mpl.ticker.MultipleLocator( conc_x_maj_loc ) ) ax.yaxis.set_major_locator( mpl.ticker.MultipleLocator( conc_y_maj_loc ) ) ax.xaxis.set_ticklabels( x_tick_labs ) # x tick labels
waves.append(ww) specs.append(spec) corspecs.append(spec / np.interp(ww, w16, t16)) snrs.append(np.median(spec/espec)) especs.append(espec) corespecs.append(espec / np.interp(ww, w16, t16)) py.close('all') tlines = [] py.ioff() for ii in range(len(waves)): losnr = signal.medfilt(corspecs[ii]/corespecs[ii], 5) py.figure(1+ii) py.plot(waves[ii], corspecs[ii]) py.title('%s, <S/N> ~ %i' % (objs[ii], snrs[ii])) py.minorticks_on() py.xlabel('Wavelength [Ang]') py.ylabel('Flux (F_Lambda)') ymax = corspecs[ii].max() if (losnr>10).any(): ymax = corspecs[ii][losnr>10].max()*1.1 py.ylim(0, ymax) py.figure(1+ii+len(waves)) py.plot(waves[ii], losnr) if py.ylim()[1]>snrs[ii]*3: py.ylim(0, snrs[ii]*3) py.title('%s, <S/N> ~ %i' % (objs[ii], snrs[ii])) py.minorticks_on() py.xlabel('Wavelength [Ang]') py.ylabel('S/N') tlines.append("%s\t%1.1f\t%i" % (objs[ii], exptimes[ii], snrs[ii]))
def sp0_style( ax ): pl.xlim( sp0_x ) pl.ylim( sp0_y ) pl.minorticks_on() ax.xaxis.set_major_locator( mpl.ticker.MultipleLocator( sp0_maj_loc[0] ) ) ax.yaxis.set_major_locator( mpl.ticker.MultipleLocator( sp0_maj_loc[1] ) )