def plot_spectrograms(bsl,rec,rate,title): plt.close() fig, ax = plt.subplots(nrows=9, ncols=2, sharex='col', sharey='row') plt.subplots_adjust(wspace = .05,hspace = 0.4 ) ny_nfft=1024 i=0 while i<9: Pxx, freq, bins, im = ax[i,0].specgram(bsl[i],NFFT=ny_nfft,Fs=rate) ax[i,0].set_ylim([0, 40]) if(i==8): ax[i,0].set_xlabel("Time, seconds") ax[i,0].set_ylabel("Freq, Hz") ax[i,0].set_title(title+' baseline sleep, REM stage, Channel:'+str(i+1)) i=i+1 i=0 while i<9: Pxx, freq, bins, im = ax[i,1].specgram(rec[i],NFFT=ny_nfft,Fs=rate) #ax[i,1].ylim(0,40) ax[i,1].set_ylim([0, 40]) #ax[i,1].set_xlim([0, 10000]) #13000]) if(i==8): ax[i,1].set_xlabel("Time, seconds") #ax[i,1].set_ylabel("Freq, Hz") ax[i,1].set_title(title+' recovery sleep, REM stage, Channel:'+str(i+1)) i=i+1 plt.show() return
def plot_setup_post(figure_number = None, show = True, save_file = None, legend = True, legend_location = 0): """ Handles post-figure setup, including legends, file saving (save_file is desired filename), showing the figure, and clearing it. """ if figure_number: pyp.figure(figure_number) pyp.subplots_adjust(bottom=.5) # adjustment to give more xlabel space # change limits # pyp.xlim( xmin = 0, xmax = 10000 ) # pyp.ylim( ymin = 0, ymax = 10000 ) # pyp.ylim( (0,10000) ) # equivalent to the line above if legend: pyp.legend(loc = legend_location) if save_file: pyp.savefig(save_file) if show: pyp.show() else: pyp.clf() # clears figure if not plotted
def paired_boxplot_o(boxes): """ Wrapper around plt.boxplot to draw paired boxplots for a set of boxes. Input is the same as plt.boxplot: Array or a sequence of vectors. """ fig = plt.figure(figsize=(len(boxes) / 2.5, 4)) ax1 = fig.add_subplot(111) plt.subplots_adjust(left=0.075, right=0.95, top=0.9, bottom=0.25) bp = ax1.boxplot(boxes, notch=0, positions=np.arange(len(boxes)) + 1.5 * (np.arange(len(boxes)) / 2), patch_artist=True) [p.set_color(colors[0]) for p in bp['boxes'][::2]] [p.set_color('black') for p in bp['whiskers']] [p.set_color('black') for p in bp['fliers']] [p.set_alpha(.4) for p in bp['fliers']] [p.set_alpha(.6) for p in bp['boxes']] [p.set_edgecolor('black') for p in bp['boxes']] ax1.yaxis.grid(True, linestyle='-', which='major', color='lightgrey', alpha=0.5) # Hide these grid behind plot objects ax1.set_axisbelow(True) ax1.set_ylabel('$Log_{2}$ RNA Expression') ax1.set_xticks(3.5 * np.arange(len(boxes) / 2) + .5) return ax1, bp
def display_collision3D(collision): jets,muons,electrons,photons,met = collision lines = draw_beams() pmom = np.array(jets).transpose()[1:4].transpose() origin = np.zeros((len(jets),3)) lines += draw_jet3D(origin=origin,pmom=pmom) pmom = np.array(muons).transpose()[1:4].transpose() origin = np.zeros((len(muons),3)) lines += draw_muon3D(origin=origin,pmom=pmom) pmom = np.array(electrons).transpose()[1:4].transpose() origin = np.zeros((len(electrons),3)) lines += draw_electron3D(origin=origin,pmom=pmom) pmom = np.array(photons).transpose()[1:4].transpose() origin = np.zeros((len(photons),3)) lines += draw_photon3D(origin=origin,pmom=pmom) fig = plt.figure(figsize=(6,4),dpi=100) ax = fig.add_subplot(1,1,1) ax = fig.gca(projection='3d') plt.subplots_adjust(top=0.98,bottom=0.02,right=0.98,left=0.02) for l in lines: ax.add_line(l) ax.set_xlim(-200,200) ax.set_ylim(-200,200) ax.set_zlim(-200,200)
def plot_scatter(self, iclus): observed = rfn.read_data() fig = plt.figure(2) plt.clf() trueM = observed[iclus*self.nlos, 1] mass = observed[iclus*self.nlos:(iclus+1)*self.nlos, 2:] mass, masstype = self.get_valid_array_altogether(mass, trueM) ii = 0 for iobs in xrange(self.nobs): for jobs in xrange(iobs+1, self.nobs, 1): ax = fig.add_subplot(4, 3, ii+1) ax.plot(mass[:, iobs], mass[:, jobs], 'bo', ms=2.5) plt.subplots_adjust(**self.adjustparam) ax.xaxis.set_major_locator(plt_ticker.MaxNLocator(3)) ax.yaxis.set_major_locator(plt_ticker.MaxNLocator(3)) #ax.set_xlabel("%s/<%s>" % (self.obsname[iobs], self.obsname[iobs])) #ax.set_ylabel("%s/<%s>" % (self.obsname[jobs], self.obsname[jobs])) fontsize=9 for tick in ax.xaxis.get_major_ticks(): tick.label1.set_fontsize(fontsize) for tick in ax.yaxis.get_major_ticks(): tick.label1.set_fontsize(fontsize) ii += 1 print self.obsname[iobs], self.obsname[jobs] plt.savefig(os.path.join("paper", "figure", "scatter_%s_clus%d.eps" % (masstype, iclus)), orientation='portrait', transparent=True)
def run(self): lines = open(self.inFilename).readlines() data = [] for line in lines: data.append(float(line.strip())) x = np.asarray(data) fig = plt.figure(figsize=(7, 3)) ax = fig.add_subplot(111) plt.subplots_adjust(left = 0.15, bottom = 0.15, wspace = 0) plt.xlabel(self.options.xlab) plt.ylabel(self.options.ylab) if self.options.logy == True: ax.set_yscale('log') plt.title(self.options.title) if self.options.plotType == 'hist': plt.xlim(0,x.max()) n,bins,patches = plt.hist(x, self.options.bins, histtype='bar', color=['crimson'],normed=False, alpha=0.85) else: plt.xlim(0,x.size) line, = plt.plot(range(x.size), x, 'r-', label = self.options.label) if self.options.label: ax.legend() plt.savefig(self.outFilename)
def draw(self, description=None, ofile="test.png"): plt.clf() for f in self.funcs: f() plt.axis("off") ax = plt.gca() ax.set_aspect("equal", "datalim") f = plt.gcf() f.set_size_inches(12.8, 7.2) if description is not None: plt.text(0.025, 0.05, description, transform=f.transFigure) if self.xlim is not None: plt.xlim(*self.xlim) if self.ylim is not None: plt.ylim(*self.ylim) plt.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0) # dpi = 100 for 720p, 150 for 1080p plt.savefig(ofile, dpi=150)
def plot_spectrograms(data, rate, subject, condition): """ Creates spectrogram subplots for all 9 channels """ fig = plt.figure() # common title fname = 'Spectrogram - '+'Subject #'+subject+' '+condition+' Dataset' fig.suptitle(fname, fontsize=14, fontweight='bold') # common ylabel fig.text(0.06, 0.5, 'ylabel', ha='center', va='center', rotation='vertical', fontsize=14, fontweight='bold') # use this to stack EEG, EOG, EMG on top of each other sub_order = [1,4,7,10,2,5,3,6,9] for ch in range(0, len(data)): plt.subplot(4, 3, sub_order[ch]) plt.subplots_adjust(hspace=.6) # adds space between subplots plt.title(channel_name[ch]) Pxx, freqs, bins, im = plt.specgram(data[ch],NFFT=512,Fs=rate) plt.ylim(0,70) plt.xlabel('Time (Seconds)') plt.ylabel('Frequency (Hz)') #fig.savefig(fname+'.pdf', format='pdf') buggy resolution problem return
def plot_data(tag): data_array = tag.references[0] voltage = np.zeros(data_array.data.shape) data_array.data.read_direct(voltage) x_axis = data_array.dimensions[0] time = x_axis.axis(data_array.data_extent[0]) spike_times = tag.positions[:] feature_data_array = tag.features[0].data snippets = tag.features[0].data[:] single_snippet = tag.retrieve_feature_data(3, 0)[:] snippet_time_dim = feature_data_array.dimensions[1] snippet_time = snippet_time_dim.axis(feature_data_array.data_extent[1]) response_axis = plt.subplot2grid((2, 2), (0, 0), rowspan=1, colspan=2) single_snippet_axis = plt.subplot2grid((2, 2), (1, 0), rowspan=1, colspan=1) average_snippet_axis = plt.subplot2grid((2, 2), (1, 1), rowspan=1, colspan=1) response_axis.plot(time, voltage, color="dodgerblue", label=data_array.name) response_axis.scatter(spike_times, np.ones(spike_times.shape) * np.max(voltage), color="red", label=tag.name) response_axis.set_xlabel(x_axis.label + ((" [" + x_axis.unit + "]") if x_axis.unit else "")) response_axis.set_ylabel(data_array.label + ((" [" + data_array.unit + "]") if data_array.unit else "")) response_axis.set_title(data_array.name) response_axis.set_xlim(0, np.max(time)) response_axis.set_ylim((1.2 * np.min(voltage), 1.2 * np.max(voltage))) response_axis.legend() single_snippet_axis.plot(snippet_time, single_snippet.T, color="red", label=("snippet No 4")) single_snippet_axis.set_xlabel( snippet_time_dim.label + ((" [" + snippet_time_dim.unit + "]") if snippet_time_dim.unit else "") ) single_snippet_axis.set_ylabel( feature_data_array.label + ((" [" + feature_data_array.unit + "]") if feature_data_array.unit else "") ) single_snippet_axis.set_title("single stimulus snippet") single_snippet_axis.set_xlim(np.min(snippet_time), np.max(snippet_time)) single_snippet_axis.set_ylim((1.2 * np.min(snippets[3, :]), 1.2 * np.max(snippets[3, :]))) single_snippet_axis.legend() mean_snippet = np.mean(snippets, axis=0) std_snippet = np.std(snippets, axis=0) average_snippet_axis.fill_between( snippet_time, mean_snippet + std_snippet, mean_snippet - std_snippet, color="red", alpha=0.5 ) average_snippet_axis.plot(snippet_time, mean_snippet, color="red", label=(feature_data_array.name + str(4))) average_snippet_axis.set_xlabel( snippet_time_dim.label + ((" [" + snippet_time_dim.unit + "]") if snippet_time_dim.unit else "") ) average_snippet_axis.set_ylabel( feature_data_array.label + ((" [" + feature_data_array.unit + "]") if feature_data_array.unit else "") ) average_snippet_axis.set_title("spike-triggered average") average_snippet_axis.set_xlim(np.min(snippet_time), np.max(snippet_time)) average_snippet_axis.set_ylim((1.2 * np.min(mean_snippet - std_snippet), 1.2 * np.max(mean_snippet + std_snippet))) plt.subplots_adjust(left=0.15, top=0.875, bottom=0.1, right=0.98, hspace=0.35, wspace=0.25) plt.show()
def plot_transition(df1, df2): """ plot stage transitions df1: normal sleep (df1 = analyse(base)) df2: sleep depravation (df2 = analyse(depr)) """ N = 5 ind = np.arange(N) # the x locations for the groups width = 0.2 # the width of the bars plt.close() fig, ax = plt.subplots(nrows=6, ncols=6, sharex='col', sharey='row') plt.subplots_adjust(wspace = 0.2,hspace = 0.4 ) for i in range(0,6): # do not care about stage transitions > 5 for j in range(0,6): clef = 't' + str(i) + '-' + str(j) normal = df1[clef].tolist() mean = sum(normal) / len(normal) normal.extend([mean]) rects1 = ax[i,j].bar(ind, normal, width, color='r') depravation = df2[clef].tolist() mean = sum(depravation) / len(depravation) depravation.extend([mean]) rects2 = ax[i,j].bar(ind+width, depravation, width, color='y') ax[i,j].set_title('t' + str(i) + '-' + str(j)) ax[i,j].set_xticks(ind+width) ax[i,j].set_xticklabels( ('1', '2', '3', '4', 'Avg') )
def segmentation(self, threshold): img = self.spectrogram["data"] mask = (img > threshold).astype(np.float) hist, bin_edges = np.histogram(img, bins=60) bin_centers = 0.5*(bin_edges[:-1] + bin_edges[1:]) binary_img = mask > 0.5 plt.figure(figsize=(11,8)) plt.subplot(131) plt.imshow(img) plt.axis('off') plt.subplot(132) plt.plot(bin_centers, hist, lw=2) print(threshold) plt.axvline(threshold, color='r', ls='--', lw=2) plt.text(0.57, 0.8, 'histogram', fontsize=20, transform = plt.gca().transAxes) plt.text(0.45, 0.75, 'threshold = '+ str(threshold)[0:5], fontsize=15, transform = plt.gca().transAxes) plt.yticks([]) plt.subplot(133) plt.imshow(binary_img) plt.axis('off') plt.subplots_adjust(wspace=0.02, hspace=0.3, top=1, bottom=0.1, left=0, right=1) plt.show() print(img.max()) print(binary_img.max()) return mask
def SVD_plot(SVStreams, SValues, stachans, title=False): r"""Function to plot the singular vectors from the clustering routines, one\ plot for each stachan :type SVStreams: list of :class:Obspy.Stream :param SVStreams: See clustering.SVD_2_Stream - will assume these are\ ordered by power, e.g. first singular vector in the first stream :type SValues: list of float :param SValues: List of the singular values corresponding to the SVStreams :type stachans: list :param stachans: List of station.channel """ for stachan in stachans: print(stachan) plot_traces = [SVStream.select(station=stachan.split('.')[0], channel=stachan.split('.')[1])[0] for SVStream in SVStreams] fig, axes = plt.subplots(len(plot_traces), 1, sharex=True) axes = axes.ravel() for i, tr in enumerate(plot_traces): y = tr.data x = np.linspace(0, len(y) * tr.stats.delta, len(y)) axes[i].plot(x, y, 'k', linewidth=1.1) ylab = 'SV '+str(i+1)+'='+str(round(SValues[i] / len(SValues), 2)) axes[i].set_ylabel(ylab, rotation=0) axes[i].yaxis.set_ticks([]) print(i) axes[-1].set_xlabel('Time (s)') plt.subplots_adjust(hspace=0) if title: axes[0].set_title(title) else: axes[0].set_title(stachan) plt.show() return
def plot_transition_ratio(df1, df2): """ plot stage transitions df1: normal sleep (df1 = analyse(base)) df2: sleep depravation (df2 = analyse(depr)) """ N = 5 ind = np.arange(N) # the x locations for the groups width = 0.2 # he width of the bars plt.close() plt.rc('font', family='Arial') fig, ax = plt.subplots(nrows=6, ncols=6, sharex='col', sharey='row') fig.suptitle("Comparison of the number of stage transitions (% of total transitions) (origin stage " + u'\u2192' + " dest. stage)", fontsize=20) plt.subplots_adjust(wspace = 0.2,hspace = 0.4 ) for i in range(0,6): # do not care about stage transitions > 5 for j in range(0,6): clef = '%t' + str(i) + '-' + str(j) normal = df1[clef].tolist() mean = sum(normal) / len(normal) normal.extend([mean]) rects1 = ax[i,j].bar(ind, normal, width, color='b') depravation = df2[clef].tolist() mean = sum(depravation) / len(depravation) depravation.extend([mean]) rects2 = ax[i,j].bar(ind+width, depravation, width, color='r') for label in (ax[i,j].get_xticklabels() + ax[i,j].get_yticklabels()): label.set_fontname('Arial') label.set_fontsize(8) ax[i,j].set_title(str(i) + ' ' + u'\u2192' + ' ' + str(j)) ax[i,j].set_xticks(ind+width) ax[i,j].set_xticklabels( ('1', '2', '3', '4', 'Avg') ) ax[i,j].set_yticks(np.arange(0, 6, 2)) ax[i,j].set_ylim([0,6]) fig.legend( (rects1[0], rects2[0]), ('Baseline', 'Recovery'), loc = 'lower right', fontsize=10)
def doit(): # test it out L = 1 R = 10 theta = np.radians(np.arange(0,361)) # draw a circle plt.plot(R*np.cos(theta), R*np.sin(theta), c="b") # draw some people angles = [30, 60, 90, 120, 180, 270, 300] for l in angles: center = ( (R + 0.5*L)*np.cos(np.radians(l)), (R + 0.5*L)*np.sin(np.radians(l)) ) draw_person(center, L, np.radians(l - 90), color="r") L = 1.1*L plt.axis("off") ax = plt.gca() ax.set_aspect("equal", "datalim") plt.subplots_adjust(left=0.05, right=0.98, bottom=0.05, top=0.98) plt.axis([-1.2*R, 1.2*R, -1.2*R, 1.2*R]) f = plt.gcf() f.set_size_inches(6.0, 6.0) plt.savefig("test.png")
def plot_time_domain_waveform(fig, waveform, imag=False, mag=False, xlim=None, xlabel=r'$tc^3/GM$', ylabel_pol=r'$h_+ + i h_\times$', ylabel_amp=r'$A$', ylabel_phase=r'$\Phi$', pol_legend=True, wave_legend=False): """Plot the amplitude, phase, and polarizations of a waveform. """ # Polarization plot axes = fig.add_subplot(311) t = waveform.time hcomp = waveform.get_complex() label = r'$h_+$' if pol_legend else '' line_list = axes.plot(t, hcomp.real, ls='-', label=label) color = line_list[0].get_color() if imag: label = r'$h_\times$' if pol_legend else '' axes.plot(t, hcomp.imag, ls='--', c=color, label=label) if mag: label = r'$|h_+ + ih_\times|$' if pol_legend else '' axes.plot(waveform.time, waveform.amp, ls=':', c=color, label=label) if xlim is not None: axes.set_xlim(xlim) axes.set_ylabel(ylabel_pol, fontsize=16) axes.set_xticklabels(axes.get_xticks(), fontsize=14) axes.set_yticklabels(axes.get_yticks(), fontsize=14) axes.minorticks_on() axes.tick_params(which='major', width=2, length=8) axes.tick_params(which='minor', width=2, length=4) axes.xaxis.set_major_formatter(NullFormatter()) # get rid of x-axis numbers axes.legend(fontsize=14, loc='best', ncol=3) # Amplitude plot axes = fig.add_subplot(312) axes.plot(waveform.time, waveform.amp, c=color) if xlim is not None: axes.set_xlim(xlim) axes.set_ylabel(ylabel_amp, fontsize=16) axes.set_xticklabels(axes.get_xticks(), fontsize=14) axes.set_yticklabels(axes.get_yticks(), fontsize=14) axes.minorticks_on() axes.tick_params(which='major', width=2, length=8) axes.tick_params(which='minor', width=2, length=4) axes.xaxis.set_major_formatter(NullFormatter()) # get rid of x-axis numbers # Phase plot axes = fig.add_subplot(313) label = wave_legend if wave_legend is not False else '' axes.plot(waveform.time, waveform.phase, c=color, label=label) if xlim is not None: axes.set_xlim(xlim) axes.set_xlabel(xlabel, fontsize=16) axes.set_ylabel(ylabel_phase, fontsize=16) axes.set_xticklabels(axes.get_xticks(), fontsize=14) axes.set_yticklabels(axes.get_yticks(), fontsize=14) axes.minorticks_on() axes.tick_params(which='major', width=2, length=8) axes.tick_params(which='minor', width=2, length=4) axes.legend(fontsize=14, loc='best', ncol=2) subplots_adjust(hspace=0.07)
def plot_fits(direction_rates,fit_curve,title): """ This function takes the x-values and the y-values in units of spikes/s (found in the two columns of direction_rates and fit_curve) and plots the actual values with circles, and the curves as lines in both linear and polar plots. """ #print direction_rates # print fit_curve plt.subplots_adjust(hspace = 0.6) y_max = np.max(direction_rates[:,1]) + 5 plt.subplot(2,2,3) plt.axis([0,360,0,y_max]) plt.plot(direction_rates[:,0], direction_rates[:,1],'o') plt.plot(fit_curve[:,0],fit_curve[:,1], '-') plt.xlabel("Direction of Motion (degrees)") plt.ylabel("Firing Rate (spikes/s)") plt.title(title) plt.subplot(2,2,4, polar = True) spikecounts = direction_rates[:,1] spikecounts2 = np.append(spikecounts, direction_rates[0,1]) r = np.arange(0, 361, 45)*np.pi/180 plt.polar(r, spikecounts2,'o') plt.polar(fit_curve[:,0]*np.pi/180,fit_curve[:,1],'-', label="Firing Rate (spikes/s)") plt.title(title) plt.legend(loc=8)
def plot_ratio_cormats(): nprops = 19 cormat_yn = N.loadtxt("cormat_to_do_pca.dat") cormat_jc = N.loadtxt("corrcoeff_jc.dat", usecols=[2]) cormat_jc = cormat_jc.reshape(nprops, nprops) rat = cormat_yn/cormat_jc fig = plt.figure(1) plt.clf() plt.subplots_adjust(hspace=0.3, wspace=0.3) fontsize=8 for ip in xrange(nprops): ax = fig.add_subplot(4, 5, ip+1) ax.plot(N.arange(nprops), rat[ip, :], 'ro', ms=2.5) ax.xaxis.set_major_locator(plt_ticker.MaxNLocator(4)) ax.yaxis.set_major_locator(plt_ticker.MaxNLocator(4)) for tick in ax.xaxis.get_major_ticks(): tick.label1.set_fontsize(fontsize) for tick in ax.yaxis.get_major_ticks(): tick.label1.set_fontsize(fontsize) ii = N.where(N.abs(rat[ip, :]-1.) > 0.01)[0] print "-"*10 print "{:d}: {:}".format(ip, ii) print cormat_yn[ip, ii] print cormat_jc[ip, ii]
def trace_plot(data, ylim): clf() plt.subplots_adjust(left=0.15); plt.subplot(411) plt.plot(np.arange(0,30000*180)/30000., data[0][:30000*3*60]) plt.xticks(alpha = 0) plt.yticks(fontsize = 'large') plt.ylabel('Voltage (mV)', size = 'x-large') plt.ylim(ylim) plt.subplot(412) plt.plot(np.arange(0,30000*180)/30000.,data[1][:30000*3*60]) plt.yticks(alpha = 0) plt.xticks(alpha = 0) plt.ylim(ylim) plt.subplot(413) plt.plot(np.arange(0,30000*180)/30000.,data[2][:30000*3*60]) plt.xticks(alpha = 0) plt.yticks(alpha = 0) plt.ylim(ylim) plt.subplot(414) plt.plot(np.arange(0,30000*180)/30000., data[3][:30000*3*60]) plt.xlabel('Time (s)', size = 'x-large') plt.xticks(fontsize = 'large') plt.yticks(alpha = 0) plt.ylim(ylim)
def plot_proj_scatter(pccoefs, eval, figname): """ plot scatters using the values projected on pc """ fig = plt.figure(4) plt.clf() eval /= N.sum(eval) param = dict(fontsize='small') range = N.max(N.abs(pccoefs)) labelx = -0.15 nplt = 4 ncol = 3 nrow = 2 iplt = 1 for iprops in xrange(nplt): for jprops in xrange(iprops+1, nplt): ax = fig.add_subplot(nrow, ncol, iplt) plt.subplots_adjust(hspace=0.2, wspace=0.25, left=0.08, right=0.95, bottom=0.08, top=0.9) ax.plot(pccoefs[:, iprops], pccoefs[:, jprops], 'ro', ms=3.) plt.axis('equal') #ax.set_xlim(-range, range) #ax.set_ylim(-range, range) ax.set_xlabel('PC%d(%.2f)' % (iprops, eval[iprops]), **param) ax.set_ylabel('PC%d(%.2f)' % (jprops, eval[jprops]), **param) ax.yaxis.set_label_coords(labelx, 0.5) iplt += 1 plt.savefig(figname)
def animate_plot(w_dir=None, **kwargs): if w_dir == None: w_dir=os.getcwd() cdir = os.getcwd() files = [] os.chdir(w_dir) os.system('mkdir j_movie') D0 = plp.pload(0,w_dir=w_dir) fig = plt.figure(num=1,figsize=[7,7]) ax = fig.add_subplot(111) plt.subplots_adjust(left=0.1, bottom=0.15) frnum = kwargs.get('frames',plp.time_info(w_dir=w_dir)['time']) for i in [0,10,25,50,150,250,319,325,340,450,638]: # 50 frames D = plp.pload(i,w_dir=w_dir) Ra = da.Rad_Average() xitem = D.x1 yitem = D.x1*D.v3[:,32] # yitem = Ra.Sigma(D,ul=1.0,urho=1.0e-9,Mstar=10.0,Gammae=5.0/3.0) ax.cla() if kwargs.get('pltype','normal') == 'normal': ax.plot(xitem,yitem,'k-') if kwargs.get('pltype','normal') == 'logx': ax.semilogx(xitem,yitem,'k-') if kwargs.get('pltype','normal') == 'logy': ax.semilogy(xitem,yitem,'k-') if kwargs.get('pltype','normal') == 'loglog': ax.loglog(xitem,yitem,'k-') ax.minorticks_on() ax.set_xlabel(kwargs.get('xlabel',r'XLabel')) ax.set_ylabel(kwargs.get('ylabel',r'YLabel')) ax.set_title(kwargs.get('title',r'Title')) #ax.text(90.0,1.3,r'$N_{\rm rot} = %04d$'%i) axcolor = 'white' axtime = plt.axes([0.1, 0.01, 0.8, 0.02], axisbg=axcolor) axtime.cla() stime = Slider(axtime, 'Nsteps', 0, frnum , valinit=D.time) #plt.draw() fname = w_dir+'j_movie/_tmp%03d.png'%i print 'Saving frame', fname fig.savefig(fname) files.append(fname) print 'Making movie animation.mpg - this make take a while' os.system("mencoder 'mf://j_movie/_tmp*.png' -mf type=png:fps=10 -ovc lavc -lavcopts vcodec=wmv2 -oac copy -o j_movie/animation.mpg") os.chdir(cdir)
def plot_synth_real(real_template, synthetic, channels=False): r"""Plot multiple channels of data for real data and synthetic. :type real_template: obspy.Stream :param real_template: Stream of the real template :type synthetic: obspy.Stream :param synthetic: Stream of synthetic template :type channels: list of str :param channels: List of tuples of (station, channel) to plot, default is\ False, which plots all. """ from obspy.signal.cross_correlation import xcorr from obspy import Stream colours = ['k', 'r'] labels = ['Real', 'Synthetic'] if channels: real = [] synth = [] for stachan in channels: real.append(real_template.select(station=stachan[0], channel=stachan[1])) synth.append(synthetic.select(station=stachan[0], channel=stachan[1])) real_template = Stream(real) synthetic = Stream(synth) # Extract the station and channels stachans = list(set([(tr.stats.station, tr.stats.channel) for tr in real_template])) fig, axes = plt.subplots(len(stachans), 1, sharex=True, figsize=(5, 10)) axes = axes.ravel() for i, stachan in enumerate(stachans): real_tr = real_template.select(station=stachan[0], channel=stachan[1])[0] synth_tr = synthetic.select(station=stachan[0], channel=stachan[1])[0] shift, corr = xcorr(real_tr, synth_tr, 2) print('Shifting by: '+str(shift)+' samples') if corr < 0: synth_tr.data = synth_tr.data * -1 corr = corr * -1 if shift < 0: synth_tr.data = synth_tr.data[abs(shift):] real_tr.data = real_tr.data[0:len(synth_tr.data)] elif shift > 0: real_tr.data = real_tr.data[abs(shift):] synth_tr.data = synth_tr.data[0:len(real_tr.data)] for j, tr in enumerate([real_tr, synth_tr]): y = tr.data y = y / float(max(abs(y))) x = np.linspace(0, len(y) * tr.stats.delta, len(y)) axes[i].plot(x, y, colours[j], linewidth=2.0, label=labels[j]) axes[i].get_yaxis().set_ticks([]) ylab = stachan[0]+'.'+stachan[1]+' cc='+str(round(corr, 2)) axes[i].set_ylabel(ylab, rotation=0) plt.subplots_adjust(hspace=0) # axes[0].legend() axes[-1].set_xlabel('Time (s)') plt.show()
def mso_orbit(orbit_number, res=60): o = mex.orbits[orbit_number] start = o.start finish = o.finish et = np.arange(start, finish, res) i = np.sum(et < o.periapsis) inbound = np.arange(0, i, 60) outbound = np.arange(i + 60, et.shape[0], 60) pos = mex.mso_position(et) / mex.mars_mean_radius_km lims = (-3, 3) off = 0.2 plt.rcParams["font.size"] = 8 phi = np.linspace(-np.pi, np.pi, 100) x = 0.78 + 0.96 * np.cos(phi) / (1 + 0.9 * np.cos(phi)) y = 0.96 * np.sin(phi) / (1 + 0.9 * np.cos(phi)) f = plt.figure(figsize=(8, 4)) def panel(no, xn, yn, bs=True): plt.subplot(no, aspect="equal") if bs: plt.plot(x, y, "k--") plt.xlabel(xn + r"$ / R_M$") celsius.ylabel(yn + r"$ / R_M$", offset=off) plt.xlim(*lims) plt.ylim(*lims) plt.gca().add_patch(plt.Circle((0.0, 0.0), 1.0, fill=False)) panel(141, r"$X$", r"$\rho$") plt.title("MEX ORBIT %d" % o.number) rho = np.sqrt(pos[1] ** 2.0 + pos[2] ** 2.0) plt.plot(pos[0], rho, "k-") plt.gca().add_patch(plt.Circle((0.0, 0.0), 1.0 + 1200.0 / mex.mars_mean_radius_km, fill=False, linestyle="dotted")) plt.gca().add_patch(plt.Circle((0.0, 0.0), 1.0 + 1500.0 / mex.mars_mean_radius_km, fill=False, linestyle="dotted")) plt.gca().add_patch(plt.Circle((0.0, 0.0), 1.0 + 2000.0 / mex.mars_mean_radius_km, fill=False, linestyle="dotted")) plt.plot(pos[0, inbound], rho[inbound], "ko") plt.plot(pos[0, outbound], rho[outbound], "ko", mfc="white") panel(142, r"$X$", r"$Z$") plt.plot(pos[0], pos[2], "k-") plt.plot(pos[0, inbound], pos[2, inbound], "ko") plt.plot(pos[0, outbound], pos[2, outbound], "ko", mfc="white") panel(143, r"$X$", r"$Y$") plt.plot(pos[0], pos[1], "k-") plt.plot(pos[0, inbound], pos[1, inbound], "ko") plt.plot(pos[0, outbound], pos[1, outbound], "ko", mfc="white") panel(144, r"$Y$", r"$Z$", bs=False) plt.plot(pos[1], pos[2], "k-") plt.plot(pos[1, inbound], pos[2, inbound], "ko") plt.plot(pos[1, outbound], pos[2, outbound], "ko", mfc="white") plt.subplots_adjust(wspace=0.3, right=0.96, top=0.94, bottom=0.07)
def fourcumplot(x1,x2,x3,x4,xmin,xmax,x1leg='$x_1$',x2leg='$x_2$',x3leg='$x_3$',x4leg='$x_3$',xlabel='',ylabel='$N(x>x\')$',fig=1,sharey=False,fontsize=12,bins1=50,bins2=50,bins3=50,bins4=50): """ Script that plots the cumulative histograms of four variables x1, x2, x3 and x4 sharing the same X-axis. For each bin, Y is the fraction of the sample with values above X. Arguments: - x1,x2,x3,x4: arrays with data to be plotted - xmin,xmax: lower and upper range of plotted values, will be used to set a consistent x-range for both histograms. - x1leg, x2leg, x3leg, x4leg: legends for each histogram - xlabel: self-explanatory. - sharey: sharing the Y-axis among the histograms? - bins1,bins2,...: number of bins in each histogram - fig: which plot window should I use? Inspired by `Scipy <http://www.scipy.org/Cookbook/Matplotlib/Multiple_Subplots_with_One_Axis_Label>`_. v1 Jun. 2012: inherited from fourhists. """ pylab.rcParams.update({'font.size': fontsize}) fig=pylab.figure(fig) pylab.clf() a=fig.add_subplot(4,1,1) if sharey==True: b=fig.add_subplot(4,1,2, sharex=a, sharey=a) c=fig.add_subplot(4,1,3, sharex=a, sharey=a) d=fig.add_subplot(4,1,4, sharex=a, sharey=a) else: b=fig.add_subplot(4,1,2, sharex=a) c=fig.add_subplot(4,1,3, sharex=a) d=fig.add_subplot(4,1,4, sharex=a) a.hist(x1,bins1,label=x1leg,color='b',cumulative=-True,normed=True,histtype='stepfilled') a.legend(loc='best',frameon=False) a.set_xlim(xmin,xmax) b.hist(x2,bins2,label=x2leg,color='r',cumulative=-True,normed=True,histtype='stepfilled') b.legend(loc='best',frameon=False) c.hist(x3,bins3,label=x3leg,color='y',cumulative=-True,normed=True,histtype='stepfilled') c.legend(loc='best',frameon=False) d.hist(x4,bins4,label=x4leg,color='g',cumulative=-True,normed=True,histtype='stepfilled') d.legend(loc='best',frameon=False) pylab.setp(a.get_xticklabels(), visible=False) pylab.setp(b.get_xticklabels(), visible=False) pylab.setp(c.get_xticklabels(), visible=False) d.set_xlabel(xlabel) c.set_ylabel(ylabel) pylab.minorticks_on() pylab.subplots_adjust(hspace=0.15) pylab.draw() pylab.show()
def riemann(): # grid info xmin = 0.0 xmax = 1.0 nzones = 2 ng = 0 gr = gp.FVGrid(nzones, xmin=xmin, xmax=xmax) #------------------------------------------------------------------------ # plot a domain without ghostcells gr.draw_grid() gr.label_center(0, r"$i$", fontsize="medium") gr.label_center(1, r"$i+1$", fontsize="medium") gr.label_edge(1, r"$i+1/2$", fontsize="medium") plt.arrow(gr.xc[0]+0.05*gr.dx, 0.5, 0.12*gr.dx, 0, shape='full', head_width=0.05, head_length=0.025, lw=1, width=0.02, edgecolor="none", facecolor="r", length_includes_head=True, zorder=100) plt.arrow(gr.xc[1]-0.1*gr.dx, 0.5, -0.12*gr.dx, 0, shape='full', head_width=0.05, head_length=0.025, lw=1, width=0.02, edgecolor="none", facecolor="r", length_includes_head=True, zorder=100) gr.mark_cell_left_state(1, r"$a_{i+1/2,L}^{n+1/2}$", fontsize="large", color="b") gr.mark_cell_right_state(0, r"$a_{i+1/2,R}^{n+1/2}$", fontsize="large", color="b") gr.label_cell_center(0, r"$a_i$") gr.label_cell_center(1, r"$a_{i+1}$") plt.xlim(gr.xl[0]-0.125*gr.dx,gr.xr[2*ng+nzones-1]+0.125*gr.dx) plt.ylim(-0.25, 1.0) plt.axis("off") plt.subplots_adjust(left=0.05,right=0.95,bottom=0.05,top=0.95) f = plt.gcf() f.set_size_inches(7.0,2.0) plt.tight_layout() plt.savefig("riemann-adv.pdf")
def display_icecube_detectors(collision): fig = plt.figure(figsize=(7,5),dpi=100) ax = fig.add_subplot(1,1,1) ax = fig.gca(projection='3d') plt.subplots_adjust(top=0.98,bottom=0.02,right=0.98,left=0.02) q,t,x,y,z = get_detector_info(collision) ax.scatter(x,y,z,s=20*q)
def images(data, zero_to_one=True, show=True, subplots=None, caption=None): """ Display images that range a grid. Especially designed for probability images, ranging from 0 to 1. Parameters ---------- data : ndarray An array of images or a single image of shape. The values should range between 0 and 1 (at least, that is how they will be colorized). zero_to_one : bool If True, then 0.0 and below will be pitch black, and 1.0 and above will be chalk white. show : bool Call `pylab.show()` inside the function. subplots : tuple or None Specify the shape of the subplots manually. caption : lambda(index, element) A function that takes the index and the element (``data[index]``) and should return a string. """ import matplotlib.pylab as plt settings = { 'interpolation': 'nearest', 'cmap': plt.cm.gray, } if zero_to_one: settings['vmin'] = 0.0 settings['vmax'] = 1.0 if isinstance(data, np.ndarray) and data.ndim == 2: fig = plt.figure() plt.subplot(111).set_axis_off() plt.imshow(data, **settings) else: # TODO: Better find out pleasing aspect ratios N = len(data) if subplots is not None: sh = subplots assert len(data) <= np.prod(subplots) elif N <= 3: sh = (1, len(data)) elif N == 5 or N == 6: sh = (2, 3) elif N == 12: sh = (3, 4) else: perside = int(math.ceil(math.sqrt(len(data)))) sh = (perside,)*2 fig = plt.figure() for i, im in enumerate(data): plt.subplot(sh[0], sh[1], 1+i).set_axis_off() plt.subplots_adjust(left=0.01, right=0.99, top=0.99, bottom=0.01) plt.imshow(im, **settings) if caption is not None: plt.title(caption(i, im)) if show: plt.show()
def TwoD_Hexbin(x, panel): # plt.xlim(np.min(x), np.max(x)) # plt.ylim(np.min(y), np.max(y)) # plt.grid(True) # plt.hexbin(x, y, bins='log', cmap=plt.cm.YlOrRd_r) plt.hist(x) plt.subplots_adjust(left=0.03, right=0.98, top=0.98, bottom=0.07) panel.canvas.draw() return
def ao_plot(o): a = AISReview(o) # fig = plt.figure() fig, ax = plt.subplots(2, 1, squeeze=True, figsize=(4,4), dpi=70, num=plt.gcf().number + 1) plt.subplots_adjust(hspace=0.3,wspace=0.0, right=0.85) a.density_along_orbit(ax[0], vmax=4.) a.modb_along_orbit(ax[1], vmax=100.)
def plot_autocorrs(self, axis=0, n_rows=4, n_cols=8): """ Plot autocorrelations for all antennas """ self.current_plot = 'multi' self.ax_zoomed = False bls = self.uv.d_uv_data['BASELINE'] # Extract the relevant baselines using a truth array # bls = bls.tolist() bl_ids = set([256*i + i for i in range(1, n_rows * n_cols + 1)]) bl_truths = np.array([(b in bl_ids) for b in bls]) #print self.uv.d_uv_data['DATA'].shape #x_data = self.d_uv_data['DATA'][bl_truths,0,0,:,0,axis] # Baselines, freq and stokes #x_cplx = x_data[:,:,0] + 1j * x_data[:,:,1] x_cplx = self.stokes[axis][bl_truths] # Plot the figure #print self.uv.n_ant fig = self.sp_fig figtitle = '%s %s: %s -- %s'%(self.uv.telescope, self.uv.instrument, self.uv.source, self.uv.date_obs) for i in range(n_rows): for j in range(n_cols): ax = fig.add_subplot(n_rows, n_cols, i*n_cols + j +1) ax.set_title(self.uv.d_array_geometry['ANNAME'][i*n_cols + j], fontsize=10) #ax.set_title("%s %s"%(i, j)) x = x_cplx[i*n_cols+j::self.uv.n_ant] if self.scale_select.currentIndex() == 0 or self.scale_select.currentIndex() == 1: if x.shape[0] == self.uv.n_ant: self.plot_spectrum(ax, x, label_axes=False) else: self.plot_spectrum(ax, x, stat='max', label_axes=False) self.plot_spectrum(ax, x, stat='med', label_axes=False) self.plot_spectrum(ax, x, stat='min', label_axes=False) else: self.plot_spectrum(ax, x, label_axes=False) self.updateFreqAxis(ax) if i == n_rows-1: ax.set_xlabel('Freq') if j == 0: ax.set_ylabel('Amplitude') plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0)) plt.tick_params(axis='both', which='major', labelsize=10) plt.tick_params(axis='both', which='minor', labelsize=8) plt.xticks(rotation=30) plt.subplots_adjust(left=0.05, right=0.98, top=0.95, bottom=0.1, wspace=0.3, hspace=0.45) return fig, ax
def plot_gallery(images, titles, h, w, n_row=3, n_col=4): """Helper function to plot a gallery of portraits""" pl.figure(figsize=(1.8 * n_col, 2.4 * n_row)) pl.subplots_adjust(bottom=0, left=.01, right=.99, top=.90, hspace=.35) for i in range(n_row * n_col): pl.subplot(n_row, n_col, i + 1) pl.imshow(images[i].reshape((h, w)), cmap=pl.cm.gray) pl.title(titles[i], size=12) pl.xticks(()) pl.yticks(())
def plot_relative_error(self, show=True, save=False): ue_scaled, ve_scaled, er = self.compute_error( errors=["ue_scaled", "ve_scaled", "er"]) plot_extent = [self.x.min(), self.x.max(), self.y.min(), self.y.max()] fig3 = pl.figure(figsize=(self.figW, self.figH)) plot = fig3.add_subplot(1, 3, 1, aspect='equal') im3 = plot.imshow(ue_scaled, vmin=0, vmax=10, origin='center', extent=plot_extent, cmap='jet') plot.plot(self.Xo[:, self.dim - 1], self.Xo[:, self.dim - 2], 'or', markersize=self.marker_size) plot.set_title("GPR Rel. Error U", size=self.text_size, pad=self.title_pad) plot.set_xlim(-5, 5) plot.set_ylim(-5, 5) plot.tick_params(labelsize=self.tick_label_size) cbar = fig3.colorbar(im3, fraction=0.046, pad=0.04) cbar.ax.tick_params(labelsize=self.cbar_label_size) plot = fig3.add_subplot(1, 3, 2, aspect='equal') im3 = plot.imshow(ve_scaled, vmin=0, vmax=10, origin='center', extent=plot_extent, cmap='jet') plot.plot(self.Xo[:, self.dim - 1], self.Xo[:, self.dim - 2], 'or', markersize=self.marker_size) plot.set_title("GPR Rel. Error U", size=self.text_size, pad=self.title_pad) plot.set_xlim(-5, 5) plot.set_ylim(-5, 5) plot.tick_params(labelsize=self.tick_label_size) cbar = fig3.colorbar(im3, fraction=0.046, pad=0.04) cbar.ax.tick_params(labelsize=self.cbar_label_size) plot = fig3.add_subplot(1, 3, 3, aspect='equal') im3 = plot.imshow(er, vmin=0, vmax=10, origin='center', extent=plot_extent, cmap='jet') plot.plot(self.Xo[:, self.dim - 1], self.Xo[:, self.dim - 2], 'or', markersize=self.marker_size) plot.set_title("GPR Rel. Error U", size=self.text_size, pad=self.title_pad) plot.set_xlim(-5, 5) plot.set_ylim(-5, 5) plot.tick_params(labelsize=self.tick_label_size) cbar = fig3.colorbar(im3, fraction=0.046, pad=0.04) cbar.ax.tick_params(labelsize=self.cbar_label_size) pl.subplots_adjust(left=0.06, bottom=0.47, right=0.94, top=0.88, wspace=0.48, hspace=0.0) if show: pl.show() if save: fig3.savefig("rel_error.png", dpi=300)
ls=so.const.symbols[2],label='Narrow') plt.plot(d_bands,2*(3.0/(s1[0]/n1[0]))**2,c=so.const.colors[3], \ ls=so.const.symbols[0]) plt.plot(d_bands,2*(3.0/(s1[1]/n1[1]))**2,c=so.const.colors[3], \ ls=so.const.symbols[2]) plt.axhline(2 * (3.0 / (s189 / n189))**2, c=so.const.colors[0]) plt.axhline(2 * (3.0 / (s209 / n209))**2, c=so.const.colors[3]) #plt.xlim(4,7.5) #plt.ylim(200,4000) plt.xlabel('Band Spacing (nm)') plt.ylabel('N$_{exp}$') plt.legend(loc='best') plt.subplots_adjust(bottom=0.17, left=0.19) plt.savefig('./plots/best_filter.png') exposures = np.arange(100) def plot_potassium_setup(): plt.style.use('dark_background') fig, ax = plt.subplots(1, 1, sharex=True, figsize=(10, 6)) ax.plot(so.exo.v, so.exo.s) #ax2 = ax.twinx() # use this for stellar contamination later #ax2.set_zorder(ax.get_zorder()+1) # put ax in front of ax2 #ax2.fill_between(so.exo.v,y1=so.filt.s_alluxa_on,y2=0*so.exo.v,facecolor='m',alpha=0.5)
darkpink, lightpink =normrgb([255,20,147]), normrgb([255,182,193]) darkblue, lightblue = normrgb([0,0,128]),normrgb([135,206, 250]) for gender in genders: for pclass in classes: if gender=='male': colorscheme = [lightblue, darkblue] row=0 else: colorscheme = [lightpink, darkpink] row=1 group = traindf[(traindf.Sex==gender)&(traindf.Pclass==pclass)] group = group.groupby(['Embarked', 'Survived']).size().unstack() group = group.div(group.sum(1), axis=0) group.plot(kind='barh', ax=axes2[row, (int(pclass)-1)], color=colorscheme, stacked=True, legend=False).set_title('Class '+str(pclass)).axes.get_xaxis().set_ticks([]) plt.subplots_adjust(wspace=0.4, hspace=1.3) fhandles, flabels = axes2[1,2].get_legend_handles_labels() mhandles, mlabels = axes2[0,2].get_legend_handles_labels() plt.figlegend(fhandles, ('die', 'live'), title='Female', loc='center', bbox_to_anchor=(0.06, 0.45, 1.1, .102)) plt.figlegend(mhandles, ('die', 'live'), 'center', title='Male',bbox_to_anchor=(-0.15, 0.45, 1.1, .102)) fig2.show() def removeBadStringFromString(string, badStringList): for badString in badStringList: string = string.replace(badString, '') return string def removeBadStringFromLabels(ax, badStringList): labels = [item.get_text() for item in ax.get_yticklabels()]
#plt.ylim(-4E+05,4E+05) vel_obs.legend() #------------------------------------save figure--------------------------- plt.savefig('TNG Filtered 0.3Hz-250s', format='png', dpi=1200) #####################################figure 4###################################### plt.figure(4) fig4 = plt.figure(4) fig4.suptitle("JCJI", fontsize=14) plt.rc('xtick', labelsize=6) plt.rc('ytick', labelsize=6) plt.rc('legend', fontsize=8) plt.subplots_adjust(top=0.8) #------------------------------graph 1--------------------------------- vel_obs = fig4.add_subplot(111, label="1") vel_ = fig4.add_subplot(111, label="2", frame_on=False) tr_obs = obs[0] obs_filt = tr_obs.copy() obs_filt.filter('lowpass', freq=0.3, corners=2, zerophase=True) t_obs = np.arange(0, obs[0].stats.npts / obs[0].stats.sampling_rate, obs[0].stats.delta) vel_obs.plot(t_obs, obs_filt.data, label='Seismogram observasi', linewidth=0.5) vel_obs.set_ylabel('Kecepatan (counts)', fontsize=7) vel_obs.set_xlabel('Waktu (s)', fontsize=8) vel_obs.tick_params(axis='x', colors='b')
def pair_plot(df, var_list, var_lims, var_labels, num_inputs=4, vmax=4, bins=30, alpha=0.7, colors=None, marker='.', ms=20, clabels=True, opt='hexbin', fig=None, ax=None, figsize=[16, 12]): if fig == None: Nx = len(var_list) Ny = len(var_list) fig, ax = plt.subplots( Nx, Ny, gridspec_kw={ 'width_ratios': [2 * figsize[0] / figsize[1] for i in range(Ny - 1)] + [1], 'height_ratios': [1] + [2 for i in range(Nx - 1)], }, figsize=figsize) for i, var_name in enumerate(var_list): for j, var_name2 in enumerate(var_list): if (j < i): y = df[var_name].values x = df[var_name2].values if i >= num_inputs: if opt == 'hexbin': hexbin = ax[i, j].hexbin(x, y, gridsize=bins, cmap=Reds, mincnt=0, extent=var_lims[var_name2] + var_lims[var_name]) ax[i, j].hexbin(x, y, gridsize=bins, bins='log', cmap=Reds, vmin=0, vmax=vmax, alpha=alpha, edgecolors='none', mincnt=0, extent=var_lims[var_name2] + var_lims[var_name]) density_contour(hexbin, ax=ax[i, j], alpha=1., colors='grey', c='k', clabels=clabels) elif opt == 'scatter': if colors == None: ax[i, j].scatter(x, y, alpha=alpha, marker=marker, s=ms, color=sns.color_palette('Reds_d')[1], zorder=10000) else: ax[i, j].scatter(x, y, alpha=alpha, marker=marker, s=ms, color=colors, zorder=10000) else: if opt == 'hexbin': hexbin = ax[i, j].hexbin(x, y, gridsize=bins, cmap=Blues, mincnt=0, extent=var_lims[var_name2] + var_lims[var_name]) ax[i, j].hexbin(x, y, gridsize=bins, bins='log', cmap=Blues, vmin=0, vmax=vmax, alpha=alpha, edgecolors='none', mincnt=0, extent=var_lims[var_name2] + var_lims[var_name]) density_contour(hexbin, ax=ax[i, j], alpha=1, colors='grey', c='k', clabels=clabels) elif opt == 'scatter': if colors == None: ax[i, j].scatter( x, y, alpha=alpha, marker=marker, s=ms, color=sns.color_palette("Blues_d")[1], zorder=10000) else: ax[i, j].scatter(x, y, alpha=alpha, marker=marker, s=ms, color=colors, zorder=10000) ax[i, j].set_ylim(var_lims[var_name]) ax[i, j].set_xlim(var_lims[var_name2]) elif (i == 0) & (j < len(var_list) - 1): y = df[var_name2].values if colors == None: if i >= num_inputs: ax[i, j].hist(y, bins=bins, normed=True, range=var_lims[var_name2], lw=0, color=sns.color_palette('Reds_d')[1]) else: ax[i, j].hist(y, bins=bins, normed=True, range=var_lims[var_name2], lw=0, color=sns.color_palette('Blues_d')[1]) else: ax[i, j].hist(y, bins=bins, normed=True, range=var_lims[var_name2], lw=1, color='k', histtype=u'step') ax[i, j].set_xlim(var_lims[var_name2]) ax[i, j].set_yticklabels([]) elif (j == len(var_list) - 1) & (i > 0): x = df[var_name].values if colors == None: if i >= num_inputs: ax[i, j].hist(x, bins=bins, normed=True, range=var_lims[var_name], lw=0, color=sns.color_palette('Reds_d')[1], orientation=u'horizontal') else: ax[i, j].hist(x, bins=bins, normed=True, range=var_lims[var_name], lw=0, color=sns.color_palette('Blues_d')[1], orientation=u'horizontal') else: ax[i, j].hist(x, bins=bins, normed=True, range=var_lims[var_name], lw=1, color='k', histtype=u'step', orientation=u'horizontal') ax[i, j].set_ylim(var_lims[var_name]) ax[i, j].set_xticklabels([]) else: ax[i, j].set_visible(False) if i != 0: ax[j, i].set_yticklabels([]) if i == 0: if j > 0: ax[j, i].set_ylabel(var_labels[var_name2]) else: ax[j, i].set_ylabel('PDF') if i != len(var_list) - 1: ax[i, j].set_xticklabels([]) if i == len(var_list) - 1: if j < len(var_list) - 1: ax[i, j].set_xlabel(var_labels[var_name2]) else: ax[i, j].set_xlabel('PDF') #xticks = ax[i,j].xaxis.get_major_ticks() #xticks[-1].label1.set_visible(False) #if len(xticks)>8: # for itick in range(1,len(xticks)-1,2): # xticks[itick].label1.set_visible(False) plt.subplots_adjust( left=.1, # the left side of the subplots of the figure right=.99, # the right side of the subplots of the figure bottom=.10, # the bottom of the subplots of the figure top=.99, # the top of the subplots of the figure wspace= 0.1, # the amount of width reserved for blank space between subplots hspace=0.1 ) # the amount of height reserved for white space between subplots return fig, ax
def NR_plot(stream, NR_stream, detections, false_detections=False,\ size=(18.5,10), save=False, title=False): """ Function to plot the Network response alongside the streams used - highlights detection times in the network response :type stream: :class: obspy.Stream :param stream: Stream to plot :type NR_stream: :class: obspy.Stream :param NR_stream: Stream for the network response :type detections: List of datetime objects :param detections: List of the detections :type false_detections: List of datetime :param false_detections: Either False (default) or list of false detection\ times :type size: tuple :param size: Size of figure, default is (18.5,10) :type save: bool :param save: Save figure or plot to screen, if not False, must be string of\ save path :type title: str :param title: String for the title of the plot, set to False """ import datetime as dt import matplotlib.dates as mdates fig, axes = plt.subplots(len(stream) + 1, 1, sharex=True, figsize=size) if len(stream) > 1: axes = axes.ravel() else: return mintime = stream.sort(['starttime'])[0].stats.starttime stream.sort(['network', 'station', 'starttime']) for i, tr in enumerate(stream): delay = tr.stats.starttime - mintime delay *= tr.stats.sampling_rate y = tr.data x=[tr.stats.starttime + dt.timedelta(seconds=s/tr.stats.sampling_rate)\ for s in xrange(len(y))] x = mdates.date2num(x) axes[i].plot(x, y, 'k', linewidth=1.1) axes[i].set_ylabel(tr.stats.station + '.' + tr.stats.channel, rotation=0) axes[i].yaxis.set_ticks([]) axes[i].set_xlim(x[0], x[-1]) # Plot the network response tr = NR_stream[0] delay = tr.stats.starttime - mintime delay *= tr.stats.sampling_rate y = tr.data x=[tr.stats.starttime + dt.timedelta(seconds=s/tr.stats.sampling_rate)\ for s in range(len(y))] x = mdates.date2num(x) axes[i].plot(x, y, 'k', linewidth=1.1) axes[i].set_ylabel(tr.stats.station + '.' + tr.stats.channel, rotation=0) axes[i].yaxis.set_ticks([]) axes[-1].set_xlabel('Time') axes[-1].set_xlim(x[0], x[-1]) # Plot the detections! ymin, ymax = axes[-1].get_ylim() if false_detections: for detection in false_detections: xd = mdates.date2num(detection) axes[-1].plot((xd, xd), (ymin, ymax), 'k--', linewidth=0.5, alpha=0.5) for detection in detections: xd = mdates.date2num(detection) axes[-1].plot((xd, xd), (ymin, ymax), 'r--', linewidth=0.75) # Set formatters for x-labels mins = mdates.MinuteLocator() if (tr.stats.endtime.datetime-tr.stats.starttime.datetime).total_seconds() >= 10800\ and (tr.stats.endtime.datetime-tr.stats.starttime.datetime).total_seconds() <= 25200: hours = mdates.MinuteLocator(byminute=[0, 15, 30, 45]) elif (tr.stats.endtime.datetime - tr.stats.starttime.datetime).total_seconds() <= 1200: hours = mdates.MinuteLocator(byminute=range(0, 60, 2)) elif (tr.stats.endtime.datetime-tr.stats.starttime.datetime).total_seconds() > 25200\ and (tr.stats.endtime.datetime-tr.stats.starttime.datetime).total_seconds() <= 172800: hours = mdates.HourLocator(byhour=range(0, 24, 3)) elif (tr.stats.endtime.datetime - tr.stats.starttime.datetime).total_seconds() > 172800: hours = mdates.DayLocator() else: hours = mdates.MinuteLocator(byminute=range(0, 60, 5)) hrFMT = mdates.DateFormatter('%Y/%m/%d %H:%M:%S') axes[-1].xaxis.set_major_locator(hours) axes[-1].xaxis.set_major_formatter(hrFMT) axes[-1].xaxis.set_minor_locator(mins) plt.gcf().autofmt_xdate() axes[-1].fmt_xdata = mdates.DateFormatter('%Y/%m/%d %H:%M:%S') plt.subplots_adjust(hspace=0) if title: axes[0].set_title(title) if not save: plt.show() plt.close() else: plt.savefig(save) return
def plotreport(self, lc_data, ext_image=None, save=False): time = lc_data[:, 0] flux = lc_data[:, 1] xpos = lc_data[:, 2] ypos = lc_data[:, 3] pixa = lc_data[:, 4] msky = lc_data[:, 5] #searching NaN value in flux nani = np.where(np.isnan(lc_data[:, 1]) == 1) # transferring list to array nan_array = np.asarray(nani[0]) #remove NaN elements from data vali = np.where(np.isnan(lc_data[:, 1]) == 0) flux_sans_NaN = lc_data[vali, 1] m_flux = np.median(flux_sans_NaN) std_flux = np.std(flux_sans_NaN) # check total number of pixels in aperture less than 3-sigam of median value tnp_index = np.where(pixa < np.median(pixa) - np.std(pixa) * 3.0) plt.clf() plt.figure(1, figsize=(8, 11)) plt.subplots_adjust(hspace=0.2) win2 = plt.subplot(411) win2.plot(time, flux, 'k-', drawstyle='steps-mid') win2.plot(time[tnp_index], time[tnp_index] * 0.0 + (m_flux + 3.0 * std_flux), 'rv') if nan_array.size > 0: for index in range(nan_array.size): win2.axvline(x=time[nan_array[index]], color='r', ls='--') win2.axhline(y=(m_flux - 3.0 * std_flux), color='r', ls='-.') win2.axhline(y=(m_flux + 3.0 * std_flux), color='r', ls='-.') win2.set_xlim(0, time[-1]) win2.set_ylim(0, m_flux + 5.0 * std_flux) win2.set_ylabel('Intensity (count)') win2.set_title('Light Curves: ' + op.basename(self.filename) + ' [f' + str(self.fibre) + ']') win1 = plt.subplot(412, sharex=win2) win1.plot(time, xpos, 'g.', label='x') win1.plot(time, ypos, 'b.', label='y') #an = np.linspace(0,2*np.pi,359) #win1.imshow(ext_image[0], cmap=plt.cm.gray, vmin=10, vmax=1000) #win1.plot(5*np.sin(an)+xpos[0], 5*np.cos(an)+ypos[0], 'r-') #win1.plot(10*np.sin(an)+xpos[0], 10*np.cos(an)+ypos[0], 'r--') win1.set_xlim(0, time[-1]) win1.set_ylim(0, 40) win1.set_ylabel('Position') win1.legend() win3 = plt.subplot(413, sharex=win2) win3.plot(time, pixa, 'k-', drawstyle='steps-mid') espected_pixa = np.pi * self.aperture**2 win3.axhline(y=espected_pixa, color='r', ls='--') if nan_array.size > 0: for index in range(nan_array.size): win3.axvline(x=time[nan_array[index]], color='r', ls='--') win3.set_xlim(0, time[-1]) win3.set_ylim( np.mean(pixa) - 6.0 * np.std(pixa), np.mean(pixa) + 6.0 * np.std(pixa)) win3.set_ylabel('Pixel') win3.set_title('Total pixels in aperture (%2d)' % (self.aperture)) win4 = plt.subplot(414, sharex=win2) if nan_array.size > 0: for index in range(nan_array.size): win4.axvline(x=time[nan_array[index]], color='r', ls='--') win4.plot(time, msky, 'k-', drawstyle='steps-mid') win4.set_xlim(0, time[-1]) win4.set_xlabel('Time (sec)') win4.set_ylabel('Sky value (count/pixel)') win4.set_title('Median sky value') xticklabels = win1.get_xticklabels() + win2.get_xticklabels( ) + win3.get_xticklabels() plt.setp(xticklabels, visible=False) plt.show() if save == 1: save_filename = 'f' + str(self.fibre) + '_' + op.basename( self.filename)[:-4] + 'png' plt.savefig(save_filename, format='png')
plt.subplot(2, 3, 2) plt.errorbar(data2[7:14, 0], data2[7:14, 1], marker=".") plt.title("l1 = 2, l2 = 3") plt.xlabel("N") plt.ylabel("<r2>") plt.grid() plt.subplot(2, 3, 3) plt.errorbar(data2[14:21, 0], data2[14:21, 1], marker=".") plt.title("l1 = 3, l2 = 4") plt.xlabel("N") plt.ylabel("<r2>") plt.grid() plt.subplot(2, 3, 4) plt.errorbar(data2[21:28, 0], data2[21:28, 1], marker=".") plt.title("l1 = 4, l2 = 5") plt.xlabel("N") plt.ylabel("<r2>") plt.grid() plt.subplot(2, 3, 5) plt.errorbar(data2[28:, 0], data2[28:, 1], marker=".") plt.title("l1 = 5, l2 = 6") plt.xlabel("N") plt.ylabel("<r2>") plt.grid() plt.subplots_adjust(hspace=.3) plt.savefig("plots2.png")
def plot_by_subs(data, output_name, colors, shapes, sub_ids, loc_ids, roi_name, figsize=(15, 5)): """ Plot_by_subs takes a data rec_array and loops through three measures: fa, md, and vol_vox and plots each on separate plots with the x-axis representing the individual subjects Required: data rec_array (eg: data) output_name (eg: results_dir/'plot_by_subs.png') colors (eg: colors) shapes (eg: shapes) sub_ids (eg: sub_ids) loc_ids (eg: loc_ids) Optional: figsize (default 15 x 5) Example usage: plot_by_subs(data=data, output_name=results_dir/'plot_by_subs.png', colors=colors, shapes=shapes, sub_ids=sub_ids, loc_ids=loc_ids, figsize=(15,5)) """ #========================================================================== import numpy as np import matplotlib.pylab as plt from matplotlib.ticker import MaxNLocator #========================================================================== fig = plt.figure(figsize=figsize) ax1 = plt.subplot(131) ax2 = plt.subplot(132) ax3 = plt.subplot(133) ax = [ax1, ax2, ax3] # Loop through the three measures (FA, MD, VOL_VOX) for count, measure in enumerate(['fa', 'md', 'vol_vox']): # Now loop through the subjects and the locations for i, sub in enumerate(sub_ids): for j, loc in enumerate(loc_ids): # Assign the correct color and shape for the marker c = colors[j, i] m = shapes[j] # Mask the data so you only have this sub at this loc's numbers mask = (data['sub'] == sub) & (data['loc_id'] == loc) # Find the number of data points you have for this sub at this location n = np.sum(mask) if n > 1: # If you have more than one data point then we're going to plot # the individual points (kinda small and a little transparent) ax[count].scatter(np.ones(n) * sub, data[measure][mask], c=c, edgecolor=c, marker=m, s=20, alpha=0.5) # ... connect them with a line ... ax[count].plot(np.ones(n) * sub, data[measure][mask], c=c) # And for everyone we'll plot the average # (which is just the data if you only have one point) mean = np.average(data[measure][mask]) ax[count].scatter(sub, mean, c=c, edgecolor=c, marker=m, s=50) # Set the y limits # This is to deal with very small numbers (the MaxNLocator gets all turned around!) buffer = (np.max(data[measure]) - np.min(data[measure])) / 10 upper = np.max(data[measure]) + buffer lower = np.min(data[measure]) - buffer ax[count].set_ybound(upper, lower) # Set the axis labels ax[count].set_ylabel('{}'.format(measure.upper())) ax[count].set_xlabel('Subject ID') # Adjust the power limits so that you use scientific notation on the y axis plt.ticklabel_format(style='sci', axis='y') [a.yaxis.major.formatter.set_powerlimits((-3, 3)) for a in ax] # Adjust the y axis ticks so that there are 6 at sensible places [a.yaxis.set_major_locator(MaxNLocator(6)) for a in ax] # Set the xaxis ticks to be sensible [a.xaxis.set_major_locator(MaxNLocator(4)) for a in ax] # Set the x axis ticks to be at the sub_ids [a.set_xticks(sub_ids) for a in ax] # Set the overall title fig.suptitle('Region of interest: {}'.format(roi_name), fontsize=20) plt.subplots_adjust(top=0.85) # And now save it plt.savefig(output_name, bbox_inches=0, facecolor='w', edgecolor='w', transparent=True)
def pair_plot_last_row(df, var_list, var_lims, var_labels, num_inputs=4, vmax=4, bins=30, alpha=0.7, colors=None, marker='.', ms=20, clabels=True, opt='hexbin', fig=None, ax=None, figsize=[12, 3], xlabels=True): if fig == None: fig, ax = plt.subplots(1, len(var_list), gridspec_kw={ 'width_ratios': [2 for i in range(len(var_list) - 1)] + [1] }, figsize=figsize) i = 0 var_name = var_list[-1] for j, var_name2 in enumerate(var_list): if (j < len(var_list) - 1): y = df[var_name].values x = df[var_name2].values if opt == 'hexbin': hexbin = ax[j].hexbin(x, y, gridsize=bins, cmap=Reds, mincnt=0, extent=var_lims[var_name2] + var_lims[var_name]) ax[j].hexbin(x, y, gridsize=bins, bins='log', cmap=Reds, vmin=0, vmax=vmax, alpha=alpha, edgecolors='none', mincnt=0, extent=var_lims[var_name2] + var_lims[var_name]) density_contour(hexbin, ax=ax[j], alpha=1., colors='grey', c='k', clabels=clabels) elif opt == 'scatter': if colors == None: ax[j].scatter(x, y, alpha=alpha, marker=marker, s=ms, color=sns.color_palette('Reds_d')[1], zorder=10000) else: ax[j].scatter(x, y, alpha=alpha, marker=marker, s=ms, color=colors, zorder=10000) ax[j].set_ylim(var_lims[var_name]) ax[j].set_xlim(var_lims[var_name2]) else: x = df[var_name].values if colors == None: ax[j].hist(x, bins=bins, normed=True, range=var_lims[var_name], lw=0, color=sns.color_palette('Reds_d')[1], orientation=u'horizontal') else: ax[j].hist(x, bins=bins, normed=True, range=var_lims[var_name], lw=1, color='k', histtype=u'step', orientation=u'horizontal') ax[j].set_ylim(var_lims[var_name]) ax[j].set_yticklabels([]) if j != 0: ax[j].set_yticklabels([]) else: ax[j].set_ylabel(var_labels[var_name]) if xlabels: if j < len(var_list) - 1: ax[j].set_xlabel(var_labels[var_name2]) xticks = ax[0].xaxis.get_major_ticks() xticks[0].label1.set_visible(False) else: ax[j].set_xticklabels([]) ax[j].set_xlabel('PDF') else: ax[j].set_xticklabels([]) plt.subplots_adjust( left=.07, # the left side of the subplots of the figure right=.99, # the right side of the subplots of the figure bottom=.25, # the bottom of the subplots of the figure top=.95, # the top of the subplots of the figure wspace= 0.1, # the amount of width reserved for blank space between subplots hspace=0.1 ) # the amount of height reserved for white space between subplots return fig, ax
print(filename) image_name = "D:/IDC_regular_ps50_idx5/9135/1/9135_idx5_x1701_y1851_class1.png" #Image to be used as query def plotImage(image_location): image = cv2.imread(image_name) image = cv2.resize(image, (50,50)) plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)); plt.axis('off') return plotImage(image_name) # Plot Multiple Images bunchOfImages = imagePatches i_ = 0 plt.rcParams['figure.figsize'] = (10.0, 10.0) plt.subplots_adjust(wspace=0, hspace=0) for l in bunchOfImages[:25]: im = cv2.imread(l) im = cv2.resize(im, (50, 50)) plt.subplot(5, 5, i_+1) #.set_title(l) plt.imshow(cv2.cvtColor(im, cv2.COLOR_BGR2RGB)); plt.axis('off') i_ += 1 def randomImages(a): r = random.sample(a, 4) plt.figure(figsize=(16,16)) plt.subplot(131) plt.imshow(cv2.imread(r[0])) plt.subplot(132) plt.imshow(cv2.imread(r[1])) plt.subplot(133)
# # Apply the newly found best focus value: # if float(optimum_focus) > 1.5 and float(optimum_focus) < 3.5: # try: # print set_tsi.set_position_instrumental_hexapod_z_offset(param=float(optimum_focus)) # except Exception,e: # print e # print "Could not preset focus value of hexapod" # else: # print "The focus found was not within accepted values..." # except Exception,e: # print e plt.figure(figsize=(10.0, 8.0), dpi=40, facecolor='w', edgecolor='k') plt.subplots_adjust(left=0.15, bottom=0.20, right=0.95, top=0.90, wspace=0.4, hspace=0.3) plt.plot(numpy.array(focus_arr), numpy.array(fwhm_arr), 'r*') plt.plot(numpy.array(new_focus_arr), numpy.array(new_fwhm_arr), 'b*') plt.xlim([min(focus_arr) - 0.1, max(focus_arr) + 0.1]) plt.ylim( [min(numpy.array(fwhm_arr)) - 1.0, max(numpy.array(fwhm_arr)) + 1.0]) plt.ylabel("FWHM [arcseconds]") plt.xlabel("Focus [mm]")
import matplotlib.pylab as plt plt.rcParams['ytick.major.pad'] = '12' from numpy import linspace plt.ion() bias = 6. layers = 24 layer_list = linspace(-(layers - 1.) / 2., (layers - 1.) / 2., layers) v = linspace(-bias / 2, bias / 2, layers) fig = plt.figure() plt.plot(layer_list, v, 'b-o', label="V") leg = plt.legend(loc="best", prop={'size': 30}) leg.draw_frame(False) plt.xlim(-12, 12) plt.xlabel("n", fontsize=30) plt.ylabel("V(n)", fontsize=30) plt.xticks(fontsize=30) plt.yticks(fontsize=30) plt.subplots_adjust(left=0.2, right=0.975, top=0.95, bottom=0.2) fig.set_size_inches(10, 7) plt.savefig("test.pdf") raw_input()
def plot_kukv(self, show=True, save=False): plot_extent = [self.x.min(), self.x.max(), self.y.min(), self.y.max()] raw_ku = self.ku raw_kv = self.kv ku = np.sqrt(self.ku) kv = np.sqrt(self.kv) fig3 = pl.figure(figsize=(self.figW, self.figH)) plot = fig3.add_subplot(1, 3, 1, aspect='equal') im5 = plot.imshow(ku, vmin=0, vmax=0.5, origin='center', extent=plot_extent, cmap='jet') plot.plot(self.Xo[:, self.dim - 1], self.Xo[:, self.dim - 2], 'or', markersize=self.marker_size) plot.set_title("GPR Ku (Standard Deviation)", size=self.text_size) plot.set_xlim(-5, 5) plot.set_ylim(-5, 5) fig3.colorbar(im5, fraction=0.046, pad=0.04) plot = fig3.add_subplot(1, 3, 2, aspect='equal') im6 = plot.imshow(kv, vmin=0, vmax=0.5, origin='center', extent=plot_extent, cmap='jet') plot.plot(self.Xo[:, self.dim - 1], self.Xo[:, self.dim - 2], 'or', markersize=self.marker_size) plot.set_title("GPR Ku (Standard Deviation)", size=self.text_size) plot.set_xlim(-5, 5) plot.set_ylim(-5, 5) fig3.colorbar(im6, fraction=0.046, pad=0.04) plot = fig3.add_subplot(1, 3, 3, aspect='equal') im7 = plot.imshow(np.sqrt( np.divide(np.add(np.power(raw_ku, 2), np.power(raw_kv, 2)), 2)), vmin=0, vmax=0.5, origin='center', extent=plot_extent, cmap='jet') plot.plot(self.Xo[:, self.dim - 1], self.Xo[:, self.dim - 2], 'or', markersize=self.marker_size) plot.set_title("GPR Ku (Standard Deviation)", size=self.text_size) plot.set_xlim(-5, 5) plot.set_ylim(-5, 5) fig3.colorbar(im7, fraction=0.046, pad=0.04) pl.subplots_adjust(left=0.05, bottom=0.47, right=0.95, top=0.88, wspace=0.35, hspace=0.0) if show: pl.show() if save: fig3.savefig("kukv.png", dpi=300)
def multi_event_singlechan(streams, picks, clip=10.0, pre_pick=2.0,\ freqmin=False, freqmax=False, realign=False, \ cut=(-3.0,5.0), PWS=False, title=False): """ Function to plot data from a single channel at a single station for multiple events - data will be alligned by their pick-time given in the picks :type streams: List of :class:obspy.stream :param streams: List of the streams to use, can contain more traces than\ you plan on plotting :type picks: List of :class:PICK :param picks: List of picks, one for each stream :type clip: float :param clip: Length in seconds to plot, defaults to 10.0 :type pre_pick: Float :param pre_pick: Length in seconds to extract and plot before the pick,\ defaults to 2.0 :type freqmin: float :param freqmin: Low cut for bandpass in Hz :type freqmax: float :param freqmax: High cut for bandpass in Hz :type realign: Bool :param realign: To compute best alignement based on correlation or not. :type cut: tuple: :param cut: tuple of start and end times for cut in seconds from the pick :type PWS: bool :param PWS: compute Phase Weighted Stack, if False, will compute linear stack :type title: str :param title: Plot title. :returns: Alligned and cut traces, and new picks """ from eqcorrscan.utils import stacking import copy from eqcorrscan.core.match_filter import normxcorr2 from obspy import Stream fig, axes = plt.subplots(len(picks) + 1, 1, sharex=True, figsize=(7, 12)) axes = axes.ravel() traces = [] al_traces = [] # Keep input safe plist = copy.deepcopy(picks) st_list = copy.deepcopy(streams) for i, pick in enumerate(plist): if st_list[i].select(station=pick.station, \ channel='*'+pick.channel[-1]): tr=st_list[i].select(station=pick.station, \ channel='*'+pick.channel[-1])[0] else: print 'No data for ' + pick.station + '.' + pick.channel continue tr.detrend('linear') if freqmin: tr.filter('bandpass', freqmin=freqmin, freqmax=freqmax) if realign: tr_cut = tr.copy() tr_cut.trim(pick.time+cut[0], pick.time+cut[1],\ nearest_sample=False) if len(tr_cut.data) <= 0.5 * (cut[1] - cut[0]) * tr_cut.stats.sampling_rate: print 'Not enough in the trace for ' + pick.station + '.' + pick.channel print 'Suggest removing pick from sfile at time ' + str( pick.time) else: al_traces.append(tr_cut) else: tr.trim(pick.time-pre_pick, pick.time+clip-pre_pick,\ nearest_sample=False) if len(tr.data) == 0: print 'No data in the trace for ' + pick.station + '.' + pick.channel print 'Suggest removing pick from sfile at time ' + str(pick.time) continue traces.append(tr) if realign: shift_len = int(0.25 * (cut[1] - cut[0]) * al_traces[0].stats.sampling_rate) shifts = stacking.align_traces(al_traces, shift_len) for i in xrange(len(shifts)): print 'Shifting by ' + str(shifts[i]) + ' seconds' pick.time -= shifts[i] traces[i].trim(pick.time - pre_pick, pick.time + clip-pre_pick,\ nearest_sample=False) # We now have a list of traces traces = [(trace, trace.stats.starttime.datetime) for trace in traces] traces.sort(key=lambda tup: tup[1]) traces = [trace[0] for trace in traces] # Plot the traces for i, tr in enumerate(traces): y = tr.data x = np.arange(len(y)) x = x / tr.stats.sampling_rate # convert to seconds axes[i + 1].plot(x, y, 'k', linewidth=1.1) # axes[i+1].set_ylabel(tr.stats.starttime.datetime.strftime('%Y/%m/%d %H:%M'),\ # rotation=0) axes[i + 1].yaxis.set_ticks([]) traces = [Stream(trace) for trace in traces] if PWS: linstack = stacking.PWS_stack(traces) else: linstack = stacking.linstack(traces) tr=linstack.select(station=picks[0].station, \ channel='*'+picks[0].channel[-1])[0] y = tr.data x = np.arange(len(y)) x = x / tr.stats.sampling_rate axes[0].plot(x, y, 'r', linewidth=2.0) axes[0].set_ylabel('Stack', rotation=0) axes[0].yaxis.set_ticks([]) for i, slave in enumerate(traces): cc = normxcorr2(tr.data, slave[0].data) axes[i + 1].set_ylabel('cc=' + str(round(np.max(cc), 2)), rotation=0) axes[i+1].text(0.9, 0.15, str(round(np.max(slave[0].data))), \ bbox=dict(facecolor='white', alpha=0.95),\ transform=axes[i+1].transAxes) axes[i+1].text(0.7, 0.85, slave[0].stats.starttime.datetime.strftime('%Y/%m/%d %H:%M:%S'), \ bbox=dict(facecolor='white', alpha=0.95),\ transform=axes[i+1].transAxes) axes[-1].set_xlabel('Time (s)') if title: axes[0].set_title(title) plt.subplots_adjust(hspace=0) plt.show() return traces, plist
def visualize_clusters(seqs, true_systems, true_cluster_ids, transform_fns, plot_filepath): """Visualizes learned params with colors of ground truth clusters. Only plots the first two dimensions of learned params. Args: seqs: A list of numpy arrays. true_systems: A list of LinearDynamicalSystem objects. true_cluster_ids: A numpy array of ground truth cluster ids. transform_fns: The transfrom fns for clustering. filepath: Path to save the plot. """ num_subplots = len(transform_fns) subplot_id = 1 subplot_cols = (num_subplots + 1) / 2 pylab.figure(figsize=(4 * 2, 4 * subplot_cols)) if true_systems is not None: num_subplots += 1 subplot_cols = (num_subplots + 1) / 2 pylab.figure(figsize=(4 * 2, 4 * subplot_cols)) pylab.subplot(subplot_cols, 2, subplot_id) subplot_id += 1 ax = sns.scatterplot(x=[a.get_spectrum()[0] for a in true_systems], y=[a.get_spectrum()[1] for a in true_systems], palette=sns.color_palette( 'Set2', np.max(true_cluster_ids) + 1), hue=true_cluster_ids) ax.set(xlabel='true eig value 1', ylabel='true eig value 2') ax.set_title('Ground Truth') plot_data_collection = None for i, k in enumerate(transform_fns.keys()): pylab.subplot(subplot_cols, 2, subplot_id) subplot_id += 1 learned_params = [transform_fns[k](s) for s in seqs] # pylint: disable=g-complex-comprehension plot_data = {str(i): [p[i] for p in learned_params] for i \ in xrange(len(learned_params[0]))} plot_data['method'] = [k] * len(learned_params) plot_data['true_cluster_id'] = list(true_cluster_ids) if plot_data_collection is None: plot_data_collection = plot_data else: for data_key in plot_data: plot_data_collection[data_key].extend(plot_data[data_key]) ax = sns.scatterplot(x=[p[0] for p in learned_params], y=[p[1] for p in learned_params], palette=sns.color_palette( 'Set2', len(np.unique(true_cluster_ids))), hue=true_cluster_ids) ax.set(xlabel='Learned param 1', ylabel='Learned param 2') ax.set_title(k) pd.DataFrame(plot_data_collection).to_csv(plot_filepath + '_data.csv') pylab.subplots_adjust(hspace=0.3, wspace=0.4) output = six.StringIO() pylab.savefig(output, format='png') image = output.getvalue() with open(plot_filepath, 'w+') as f: f.write(image)
def pretty_template_plot(template, size=(18.5, 10.5), save=False, title=False,\ background=False): """ Function to make a pretty plot of a single template, designed to work better than the default obspy plotting routine for short data lengths. :type template: :class: obspy.Stream :param template: Template stream to plot :type size: tuple :param size: tuple of plot size :type save: Boolean :param save: if False will plot to screen, if True will save :type title: Boolean :param title: String if set will be the plot title :type backrgound: :class: obspy.stream :param background: Stream to plot the template within. """ fig, axes = plt.subplots(len(template), 1, sharex=True, figsize=size) if len(template) > 1: axes = axes.ravel() else: return if not background: mintime = template.sort(['starttime'])[0].stats.starttime else: mintime = background.sort(['starttime'])[0].stats.starttime template.sort(['network', 'station', 'starttime']) for i, tr in enumerate(template): delay = tr.stats.starttime - mintime delay *= tr.stats.sampling_rate y = tr.data x = np.arange(len(y)) x += delay x = x / tr.stats.sampling_rate # x=np.arange(delay, (len(y)*tr.stats.sampling_rate)+delay,\ # tr.stats.sampling_rate) if background: btr=background.select(station=tr.stats.station, \ channel=tr.stats.channel)[0] bdelay = btr.stats.starttime - mintime bdelay *= btr.stats.sampling_rate by = btr.data bx = np.arange(len(by)) bx += bdelay bx = bx / btr.stats.sampling_rate axes[i].plot(bx, by, 'k', linewidth=1) axes[i].plot(x, y, 'r', linewidth=1.1) else: axes[i].plot(x, y, 'k', linewidth=1.1) print tr.stats.station + ' ' + str(len(x)) + ' ' + str(len(y)) axes[i].set_ylabel(tr.stats.station + '.' + tr.stats.channel, rotation=0) axes[i].yaxis.set_ticks([]) axes[i - 1].set_xlabel('Time (s) from start of template') plt.subplots_adjust(hspace=0) if title: axes[0].set_title(title) if not save: plt.show() plt.close() else: plt.savefig(save)
#Give a sample plot pl.subplot(337) bl = bls[0] i,j = np.argwhere(AntNos==bl[0]).squeeze(),np.argwhere(AntNos==bl[1]).squeeze() pl.vlines(D_ij[pol][bl]/bl_len[bl],0,1.1,color='k') pl.vlines((Tau[pol][i]-Tau[pol][j])/bl_len[bl],0,1.1,color='r') pl.vlines((-1,1),0,1.1,linestyles='dotted',color='k') pl.plot(delays/bl_len[bl],DD[pol][bl],'b') pl.title('Sample baseline, %d_%d'%bl) pl.xlim([-1.5,1.5]) pl.ylim([0,1.1]) pl.xlabel('Delay, baseline lenghth.') pl.ylabel('Amplitude') pl.subplots_adjust(wspace=0,hspace=0,top=0.95,bottom=0.05) pl.draw() figcnt += 1 #Plot a matrix of all delays for pol in pols: pl.figure(figcnt) DDD = np.zeros((Nant,Nant)) for i,ant1 in enumerate(AntNos): for j,ant2 in enumerate(AntNos): if not (ant1,ant2) in D_ij[pol].keys(): continue DDD[i,j] = D_ij[pol][(ant1,ant2)] DDD = np.ma.array(DDD,mask=np.where(DDD==0,1,0)) pl.matshow(DDD,aspect='auto') pl.colorbar() pl.draw()
def plot_synth_real(real_template, synthetic, channels=False): """ Plot multiple channels of data for real data and synthetic :type real_template: obspy.Stream :param real_template: Stream of the real template :type synthetic: obspy.Stream :param synthetic: Stream of synthetic template :type channels: List of str :param channels: List of tuples of (station, channel) to plot, default is\ False, which plots all. """ from obspy.signal.cross_correlation import xcorr from obspy import Stream colours = ['k', 'r'] labels = ['Real', 'Synthetic'] if channels: real = [] synth = [] for stachan in channels: real.append(real_template.select(station=stachan[0],\ channel=stachan[1])) synth.append(synthetic.select(station=stachan[0],\ channel=stachan[1])) real_template = Stream(real) synthetic = Stream(synth) # Extract the station and channels stachans = list(set([(tr.stats.station, tr.stats.channel)\ for tr in real_stream])) fig, axes = plt.subplots(len(stachans), 1, sharex=True, figsize=(5, 10)) axes = axes.ravel() for i, stachan in enumerate(stachans): real_tr=real_template.select(station=stachan[0],\ channel=stachan[1])[0] synth_tr=synthetic.select(station=stachan[0],\ channel=stachan[1])[0] shift, corr = xcorr(real_tr, synth_tr, 2) print 'Shifting by: ' + str(shift) + ' samples' if corr < 0: synth_tr.data = synth_tr.data * -1 corr = corr * -1 if shift < 0: synth_tr.data = synth_tr.data[abs(shift):] real_tr.data = real_tr.data[0:len(synth_tr.data)] elif shift > 0: real_tr.data = real_tr.data[abs(shift):] synth_tr.data = synth_tr.data[0:len(real_tr.data)] for j, tr in enumerate([real_tr, synth_tr]): y = tr.data y = y / float(max(abs(y))) x = np.arange(0, len(y)) x = x / tr.stats.sampling_rate axes[i].plot(x, y, colours[j], linewidth=2.0, label=labels[j]) axes[i].get_yaxis().set_ticks([]) axes[i].set_ylabel(stachan[0]+'.'+stachan[1]+' cc='+str(round(corr,2)),\ rotation=0) plt.subplots_adjust(hspace=0) # axes[0].legend() axes[-1].set_xlabel('Time (s)') plt.show()
for i in range(len(CELLS)): Rm_data[i] = 1e-6 / CELLS[i]['Gl'] soma1, stick1, params1 = adjust_model_prop(Rm_data[i], soma, stick) Rtf_model[i] = get_the_mean_transfer_resistance_to_soma( soma1, stick1, params1) print('---------------------------------------------------') print('Comparison between model and data for Tm') print('MODEL, mean = ', 1e-6 * Rtf_model.mean(), 'ms +/-', 1e-6 * Rtf_model.std()) print('---------------------------------------------------') fig, [ax, ax2] = plt.subplots(1, 2, figsize=(8, 3)) plt.subplots_adjust(bottom=.3, wspace=.4) # histogram # ax.hist(1e3*Rtf_data, color='r', label='data') ax.hist(1e-6 * Rtf_model, color='b', label='model') ax.legend(frameon=False, prop={'size': 'x-small'}, loc='best') set_plot(ax, xlabel='transfer resistance \n to soma $(M \Omega)$', ylabel='cell #') # correl Rm-Tm ax2.plot(Rm_data, 1e-6 * Rtf_model, 'ob', label='model') ax2.legend(prop={'size': 'xx-small'}, loc='best') set_plot(ax2, xlabel='somatic input \n resistance $(M \Omega)$', ylabel='transfer resistance \n to soma $(M \Omega)$') plt.show()
def select_windows(data_trace, synthetic_trace, event_latitude, event_longitude, event_depth_in_km, station_latitude, station_longitude, minimum_period, maximum_period, min_cc=0.10, max_noise=0.10, max_noise_window=0.4, min_velocity=2.4, threshold_shift=0.30, threshold_correlation=0.75, min_length_period=1.5, min_peaks_troughs=2, max_energy_ratio=10.0, min_envelope_similarity=0.2, verbose=False, plot=False): """ Window selection algorithm for picking windows suitable for misfit calculation based on phase differences. Returns a list of windows which might be empty due to various reasons. This function is really long and a lot of things. For a more detailed description, please see the LASIF paper. :param data_trace: The data trace. :type data_trace: :class:`~obspy.core.trace.Trace` :param synthetic_trace: The synthetic trace. :type synthetic_trace: :class:`~obspy.core.trace.Trace` :param event_latitude: The event latitude. :type event_latitude: float :param event_longitude: The event longitude. :type event_longitude: float :param event_depth_in_km: The event depth in km. :type event_depth_in_km: float :param station_latitude: The station latitude. :type station_latitude: float :param station_longitude: The station longitude. :type station_longitude: float :param minimum_period: The minimum period of the data in seconds. :type minimum_period: float :param maximum_period: The maximum period of the data in seconds. :type maximum_period: float :param min_cc: Minimum normalised correlation coefficient of the complete traces. :type min_cc: float :param max_noise: Maximum relative noise level for the whole trace. Measured from maximum amplitudes before and after the first arrival. :type max_noise: float :param max_noise_window: Maximum relative noise level for individual windows. :type max_noise_window: float :param min_velocity: All arrivals later than those corresponding to the threshold velocity [km/s] will be excluded. :type min_velocity: float :param threshold_shift: Maximum allowable time shift within a window, as a fraction of the minimum period. :type threshold_shift: float :param threshold_correlation: Minimum normalised correlation coeeficient within a window. :type threshold_correlation: float :param min_length_period: Minimum length of the time windows relative to the minimum period. :type min_length_period: float :param min_peaks_troughs: Minimum number of extrema in an individual time window (excluding the edges). :type min_peaks_troughs: float :param max_energy_ratio: Maximum energy ratio between data and synthetics within a time window. Don't make this too small! :type max_energy_ratio: float :param min_envelope_similarity: The minimum similarity of the envelopes of both data and synthetics. This essentially assures that the amplitudes of data and synthetics can not diverge too much within a window. It is a bit like the inverse of the ratio of both envelopes so a value of 0.2 makes sure neither amplitude can be more then 5 times larger than the other. :type min_envelope_similarity: float :param verbose: No output by default. :type verbose: bool :param plot: Create a plot of the algortihm while it does its work. :type plot: bool """ # Shortcuts to frequently accessed variables. data_starttime = data_trace.stats.starttime data_delta = data_trace.stats.delta dt = data_trace.stats.delta npts = data_trace.stats.npts synth = synthetic_trace.data data = data_trace.data times = data_trace.times() # Fill cache if necessary. if not TAUPY_MODEL_CACHE: from obspy.taup import TauPyModel # NOQA TAUPY_MODEL_CACHE["model"] = TauPyModel("AK135") model = TAUPY_MODEL_CACHE["model"] # ------------------------------------------------------------------------- # Geographical calculations and the time of the first arrival. # ------------------------------------------------------------------------- dist_in_deg = geodetics.locations2degrees(station_latitude, station_longitude, event_latitude, event_longitude) dist_in_km = geodetics.calcVincentyInverse( station_latitude, station_longitude, event_latitude, event_longitude)[0] / 1000.0 # Get only a couple of P phases which should be the first arrival # for every epicentral distance. Its quite a bit faster than calculating # the arrival times for every phase. # Assumes the first sample is the centroid time of the event. tts = model.get_travel_times(source_depth_in_km=event_depth_in_km, distance_in_degree=dist_in_deg, phase_list=["ttp"]) # Sort just as a safety measure. tts = sorted(tts, key=lambda x: x.time) first_tt_arrival = tts[0].time # ------------------------------------------------------------------------- # Window settings # ------------------------------------------------------------------------- # Number of samples in the sliding window. Currently, the length of the # window is set to a multiple of the dominant period of the synthetics. # Make sure it is an uneven number; just to have a trivial midpoint # definition and one sample does not matter much in any case. window_length = int(round(float(2 * minimum_period) / dt)) if not window_length % 2: window_length += 1 # Use a Hanning window. No particular reason for it but its a well-behaved # window and has nice spectral properties. taper = np.hanning(window_length) # ========================================================================= # check if whole seismograms are sufficiently correlated and estimate # noise level # ========================================================================= # Overall Correlation coefficient. norm = np.sqrt(np.sum(data**2)) * np.sqrt(np.sum(synth**2)) cc = np.sum(data * synth) / norm if verbose: _log_window_selection(data_trace.id, "Correlation Coefficient: %.4f" % cc) # Estimate noise level from waveforms prior to the first arrival. idx_end = int(np.ceil((first_tt_arrival - 0.5 * minimum_period) / dt)) idx_end = max(10, idx_end) idx_start = int(np.ceil((first_tt_arrival - 2.5 * minimum_period) / dt)) idx_start = max(10, idx_start) if idx_start >= idx_end: idx_start = max(0, idx_end - 10) abs_data = np.abs(data) noise_absolute = abs_data[idx_start:idx_end].max() noise_relative = noise_absolute / abs_data.max() if verbose: _log_window_selection(data_trace.id, "Absolute Noise Level: %e" % noise_absolute) _log_window_selection(data_trace.id, "Relative Noise Level: %e" % noise_relative) # Basic global rejection criteria. accept_traces = True if (cc < min_cc) and (noise_relative > max_noise / 3.0): msg = "Correlation %.4f is below threshold of %.4f" % (cc, min_cc) if verbose: _log_window_selection(data_trace.id, msg) accept_traces = msg if noise_relative > max_noise: msg = "Noise level %.3f is above threshold of %.3f" % (noise_relative, max_noise) if verbose: _log_window_selection(data_trace.id, msg) accept_traces = msg # Calculate the envelope of both data and synthetics. This is to make sure # that the amplitude of both is not too different over time and is # used as another selector. Only calculated if the trace is generally # accepted as it is fairly slow. if accept_traces is True: data_env = obspy.signal.filter.envelope(data) synth_env = obspy.signal.filter.envelope(synth) # ------------------------------------------------------------------------- # Initial Plot setup. # ------------------------------------------------------------------------- # All the plot calls are interleaved. I realize this is really ugly but # the alternative would be to either have two functions (one with plots, # one without) or split the plotting function in various subfunctions, # neither of which are acceptable in my opinion. The impact on # performance is minimal if plotting is turned off: all imports are lazy # and a couple of conditionals are cheap. if plot: import matplotlib.pylab as plt # NOQA import matplotlib.patheffects as PathEffects # NOQA if accept_traces is True: plt.figure(figsize=(18, 12)) plt.subplots_adjust(left=0.05, bottom=0.05, right=0.98, top=0.95, wspace=None, hspace=0.0) grid = (31, 1) # Axes showing the data. data_plot = plt.subplot2grid(grid, (0, 0), rowspan=8) else: # Only show one axes it the traces are not accepted. plt.figure(figsize=(18, 3)) # Plot envelopes if needed. if accept_traces is True: plt.plot(times, data_env, color="black", alpha=0.5, lw=0.4, label="data envelope") plt.plot(synthetic_trace.times(), synth_env, color="#e41a1c", alpha=0.4, lw=0.5, label="synthetics envelope") plt.plot(times, data, color="black", label="data", lw=1.5) plt.plot(synthetic_trace.times(), synth, color="#e41a1c", label="synthetics", lw=1.5) # Symmetric around y axis. middle = data.mean() d_max, d_min = data.max(), data.min() r = max(d_max - middle, middle - d_min) * 1.1 ylim = (middle - r, middle + r) xlim = (times[0], times[-1]) plt.ylim(*ylim) plt.xlim(*xlim) offset = (xlim[1] - xlim[0]) * 0.005 plt.vlines(first_tt_arrival, ylim[0], ylim[1], colors="#ff7f00", lw=2) plt.text(first_tt_arrival + offset, ylim[1] - (ylim[1] - ylim[0]) * 0.02, "first arrival", verticalalignment="top", horizontalalignment="left", color="#ee6e00", path_effects=[ PathEffects.withStroke(linewidth=3, foreground="white") ]) plt.vlines(first_tt_arrival - minimum_period / 2.0, ylim[0], ylim[1], colors="#ff7f00", lw=2) plt.text(first_tt_arrival - minimum_period / 2.0 - offset, ylim[0] + (ylim[1] - ylim[0]) * 0.02, "first arrival - min period / 2", verticalalignment="bottom", horizontalalignment="right", color="#ee6e00", path_effects=[ PathEffects.withStroke(linewidth=3, foreground="white") ]) for velocity in [6, 5, 4, 3, min_velocity]: tt = dist_in_km / velocity plt.vlines(tt, ylim[0], ylim[1], colors="gray", lw=2) if velocity == min_velocity: hal = "right" o_s = -1.0 * offset else: hal = "left" o_s = offset plt.text(tt + o_s, ylim[0] + (ylim[1] - ylim[0]) * 0.02, str(velocity) + " km/s", verticalalignment="bottom", horizontalalignment=hal, color="0.15") plt.vlines(dist_in_km / min_velocity + minimum_period / 2.0, ylim[0], ylim[1], colors="gray", lw=2) plt.text(dist_in_km / min_velocity + minimum_period / 2.0 - offset, ylim[1] - (ylim[1] - ylim[0]) * 0.02, "min surface velocity + min period / 2", verticalalignment="top", horizontalalignment="right", color="0.15", path_effects=[ PathEffects.withStroke(linewidth=3, foreground="white") ]) plt.hlines(noise_absolute, xlim[0], xlim[1], linestyle="--", color="gray") plt.hlines(-noise_absolute, xlim[0], xlim[1], linestyle="--", color="gray") plt.text(offset, noise_absolute + (ylim[1] - ylim[0]) * 0.01, "noise level", verticalalignment="bottom", horizontalalignment="left", color="0.15", path_effects=[ PathEffects.withStroke(linewidth=3, foreground="white") ]) plt.legend(loc="lower right", fancybox=True, framealpha=0.5, fontsize="small") plt.gca().xaxis.set_ticklabels([]) # Plot the basic global information. ax = plt.gca() txt = ( "Total CC Coeff: %.4f\nAbsolute Noise: %e\nRelative Noise: %.3f" % (cc, noise_absolute, noise_relative)) ax.text(0.01, 0.95, txt, transform=ax.transAxes, fontdict=dict(fontsize="small", ha='left', va='top'), bbox=dict(boxstyle="round", fc="w", alpha=0.8)) plt.suptitle("Channel %s" % data_trace.id, fontsize="larger") # Show plot and return if not accepted. if accept_traces is not True: txt = "Rejected: %s" % (accept_traces) ax.text(0.99, 0.95, txt, transform=ax.transAxes, fontdict=dict(fontsize="small", ha='right', va='top'), bbox=dict(boxstyle="round", fc="red", alpha=1.0)) plt.show() if accept_traces is not True: return [] # Initialise masked arrays. The mask will be set to True where no # windows are chosen. time_windows = np.ma.ones(npts) time_windows.mask = False if plot: old_time_windows = time_windows.copy() # Elimination Stage 1: Eliminate everything half a period before or # after the minimum and maximum travel times, respectively. # theoretical arrival as positive. min_idx = int((first_tt_arrival - (minimum_period / 2.0)) / dt) max_idx = int( math.ceil((dist_in_km / min_velocity + minimum_period / 2.0) / dt)) time_windows.mask[:min_idx + 1] = True time_windows.mask[max_idx:] = True if plot: plt.subplot2grid(grid, (8, 0), rowspan=1) _plot_mask(time_windows, old_time_windows, name="TRAVELTIME ELIMINATION") old_time_windows = time_windows.copy() # ------------------------------------------------------------------------- # Compute sliding time shifts and correlation coefficients for time # frames that passed the traveltime elimination stage. # ------------------------------------------------------------------------- # Allocate arrays to collect the time dependent values. sliding_time_shift = np.ma.zeros(npts, dtype="float32") sliding_time_shift.mask = True max_cc_coeff = np.ma.zeros(npts, dtype="float32") max_cc_coeff.mask = True for start_idx, end_idx, midpoint_idx in _window_generator( npts, window_length): if not min_idx < midpoint_idx < max_idx: continue # Slice windows. Create a copy to be able to taper without affecting # the original time series. data_window = data[start_idx:end_idx].copy() * taper synthetic_window = \ synth[start_idx: end_idx].copy() * taper # Elimination Stage 2: Skip windows that have essentially no energy # to avoid instabilities. No windows can be picked in these. if synthetic_window.ptp() < synth.ptp() * 0.001: time_windows.mask[midpoint_idx] = True continue # Calculate the time shift. Here this is defined as the shift of the # synthetics relative to the data. So a value of 2, for instance, means # that the synthetics are 2 timesteps later then the data. cc = np.correlate(data_window, synthetic_window, mode="full") time_shift = cc.argmax() - window_length + 1 # Express the time shift in fraction of the minimum period. sliding_time_shift[midpoint_idx] = (time_shift * dt) / minimum_period # Normalized cross correlation. max_cc_value = cc.max() / np.sqrt( (synthetic_window**2).sum() * (data_window**2).sum()) max_cc_coeff[midpoint_idx] = max_cc_value if plot: plt.subplot2grid(grid, (9, 0), rowspan=1) _plot_mask(time_windows, old_time_windows, name="NO ENERGY IN CC WINDOW") # Axes with the CC coeffs plt.subplot2grid(grid, (15, 0), rowspan=4) plt.hlines(0, xlim[0], xlim[1], color="lightgray") plt.hlines(-threshold_shift, xlim[0], xlim[1], color="gray", linestyle="--") plt.hlines(threshold_shift, xlim[0], xlim[1], color="gray", linestyle="--") plt.text(5, -threshold_shift - (2) * 0.03, "threshold", verticalalignment="top", horizontalalignment="left", color="0.15", path_effects=[ PathEffects.withStroke(linewidth=3, foreground="white") ]) plt.plot(times, sliding_time_shift, color="#377eb8", label="Time shift in fraction of minimum period", lw=1.5) ylim = plt.ylim() plt.yticks([-0.75, 0, 0.75]) plt.xticks([300, 600, 900, 1200, 1500, 1800]) plt.ylim(ylim[0], ylim[1] + ylim[1] - ylim[0]) plt.ylim(-1.0, 1.0) plt.xlim(xlim) plt.gca().xaxis.set_ticklabels([]) plt.legend(loc="lower right", fancybox=True, framealpha=0.5, fontsize="small") plt.subplot2grid(grid, (10, 0), rowspan=4) plt.hlines(threshold_correlation, xlim[0], xlim[1], color="0.15", linestyle="--") plt.hlines(1, xlim[0], xlim[1], color="lightgray") plt.hlines(0, xlim[0], xlim[1], color="lightgray") plt.text(5, threshold_correlation + (1.4) * 0.01, "threshold", verticalalignment="bottom", horizontalalignment="left", color="0.15", path_effects=[ PathEffects.withStroke(linewidth=3, foreground="white") ]) plt.plot(times, max_cc_coeff, color="#4daf4a", label="Maximum CC coefficient", lw=1.5) plt.ylim(-0.2, 1.2) plt.yticks([0, 0.5, 1]) plt.xticks([300, 600, 900, 1200, 1500, 1800]) plt.xlim(xlim) plt.gca().xaxis.set_ticklabels([]) plt.legend(loc="lower right", fancybox=True, framealpha=0.5, fontsize="small") # Elimination Stage 3: Mark all areas where the normalized cross # correlation coefficient is under threshold_correlation as negative if plot: old_time_windows = time_windows.copy() time_windows.mask[max_cc_coeff < threshold_correlation] = True if plot: plt.subplot2grid(grid, (14, 0), rowspan=1) _plot_mask(time_windows, old_time_windows, name="CORRELATION COEFF THRESHOLD ELIMINATION") # Elimination Stage 4: Mark everything with an absolute travel time # shift of more than # threshold_shift times the dominant period as # negative if plot: old_time_windows = time_windows.copy() time_windows.mask[np.ma.abs(sliding_time_shift) > threshold_shift] = True if plot: plt.subplot2grid(grid, (19, 0), rowspan=1) _plot_mask(time_windows, old_time_windows, name="TIME SHIFT THRESHOLD ELIMINATION") # Elimination Stage 5: Mark the area around every "travel time shift # jump" (based on the traveltime time difference) negative. The width of # the area is currently chosen to be a tenth of a dominant period to # each side. if plot: old_time_windows = time_windows.copy() sample_buffer = int(np.ceil(minimum_period / dt * 0.1)) indices = np.ma.where(np.ma.abs(np.ma.diff(sliding_time_shift)) > 0.1)[0] for index in indices: time_windows.mask[index - sample_buffer:index + sample_buffer] = True if plot: plt.subplot2grid(grid, (20, 0), rowspan=1) _plot_mask(time_windows, old_time_windows, name="TIME SHIFT JUMPS ELIMINATION") # Clip both to avoid large numbers by division. stacked = np.vstack([ np.ma.clip(synth_env, synth_env.max() * min_envelope_similarity * 0.5, synth_env.max()), np.ma.clip(data_env, data_env.max() * min_envelope_similarity * 0.5, data_env.max()) ]) # Ratio. ratio = stacked.min(axis=0) / stacked.max(axis=0) # Elimination Stage 6: Make sure the amplitudes of both don't vary too # much. if plot: old_time_windows = time_windows.copy() time_windows.mask[ratio < min_envelope_similarity] = True if plot: plt.subplot2grid(grid, (25, 0), rowspan=1) _plot_mask(time_windows, old_time_windows, name="ENVELOPE AMPLITUDE SIMILARITY ELIMINATION") if plot: plt.subplot2grid(grid, (21, 0), rowspan=4) plt.hlines(min_envelope_similarity, xlim[0], xlim[1], color="gray", linestyle="--") plt.text(5, min_envelope_similarity + (2) * 0.03, "threshold", verticalalignment="bottom", horizontalalignment="left", color="0.15", path_effects=[ PathEffects.withStroke(linewidth=3, foreground="white") ]) plt.plot(times, ratio, color="#9B59B6", label="Envelope amplitude similarity", lw=1.5) plt.yticks([0, 0.2, 0.4, 0.6, 0.8, 1.0]) plt.ylim(0.05, 1.05) plt.xticks([300, 600, 900, 1200, 1500, 1800]) plt.xlim(xlim) plt.gca().xaxis.set_ticklabels([]) plt.legend(loc="lower right", fancybox=True, framealpha=0.5, fontsize="small") # First minimum window length elimination stage. This is cheap and if # not done it can easily destabilize the peak-and-trough marching stage # which would then have to deal with way more edge cases. if plot: old_time_windows = time_windows.copy() min_length = \ min(minimum_period / dt * min_length_period, maximum_period / dt) for i in flatnotmasked_contiguous(time_windows): # Step 7: Throw away all windows with a length of less then # min_length_period the dominant periodele if (i.stop - i.start) < min_length: time_windows.mask[i.start:i.stop] = True if plot: plt.subplot2grid(grid, (26, 0), rowspan=1) _plot_mask(time_windows, old_time_windows, name="MINIMUM WINDOW LENGTH ELIMINATION 1") # ------------------------------------------------------------------------- # Peak and trough marching algorithm # ------------------------------------------------------------------------- final_windows = [] for i in flatnotmasked_contiguous(time_windows): # Cut respective windows. window_npts = i.stop - i.start synthetic_window = synth[i.start:i.stop] data_window = data[i.start:i.stop] # Find extrema in the data and the synthetics. data_p, data_t = find_local_extrema(data_window) synth_p, synth_t = find_local_extrema(synthetic_window) window_mask = np.ones(window_npts, dtype="bool") closest_peaks = find_closest(data_p, synth_p) diffs = np.diff(closest_peaks) for idx in np.where(diffs == 1)[0]: if idx > 0: start = synth_p[idx - 1] else: start = 0 if idx < (len(synth_p) - 1): end = synth_p[idx + 1] else: end = -1 window_mask[start:end] = False closest_troughs = find_closest(data_t, synth_t) diffs = np.diff(closest_troughs) for idx in np.where(diffs == 1)[0]: if idx > 0: start = synth_t[idx - 1] else: start = 0 if idx < (len(synth_t) - 1): end = synth_t[idx + 1] else: end = -1 window_mask[start:end] = False window_mask = np.ma.masked_array(window_mask, mask=window_mask) if window_mask.mask.all(): continue for j in flatnotmasked_contiguous(window_mask): final_windows.append((i.start + j.start, i.start + j.stop)) if plot: old_time_windows = time_windows.copy() time_windows.mask[:] = True for start, stop in final_windows: time_windows.mask[start:stop] = False if plot: plt.subplot2grid(grid, (27, 0), rowspan=1) _plot_mask(time_windows, old_time_windows, name="PEAK AND TROUGH MARCHING ELIMINATION") # Loop through all the time windows, remove windows not satisfying the # minimum number of peaks and troughs per window. Acts mainly as a # safety guard. old_time_windows = time_windows.copy() for i in flatnotmasked_contiguous(old_time_windows): synthetic_window = synth[i.start:i.stop] data_window = data[i.start:i.stop] data_p, data_t = find_local_extrema(data_window) synth_p, synth_t = find_local_extrema(synthetic_window) if np.min([len(synth_p), len(synth_t), len(data_p), len(data_t)]) < \ min_peaks_troughs: time_windows.mask[i.start:i.stop] = True if plot: plt.subplot2grid(grid, (28, 0), rowspan=1) _plot_mask(time_windows, old_time_windows, name="PEAK/TROUGH COUNT ELIMINATION") # Second minimum window length elimination stage. if plot: old_time_windows = time_windows.copy() min_length = \ min(minimum_period / dt * min_length_period, maximum_period / dt) for i in flatnotmasked_contiguous(time_windows): # Step 7: Throw away all windows with a length of less then # min_length_period the dominant period. if (i.stop - i.start) < min_length: time_windows.mask[i.start:i.stop] = True if plot: plt.subplot2grid(grid, (29, 0), rowspan=1) _plot_mask(time_windows, old_time_windows, name="MINIMUM WINDOW LENGTH ELIMINATION 2") # Final step, eliminating windows with little energy. final_windows = [] for j in flatnotmasked_contiguous(time_windows): # Again assert a certain minimal length. if (j.stop - j.start) < min_length: continue # Compare the energy in the data window and the synthetic window. data_energy = (data[j.start:j.stop]**2).sum() synth_energy = (synth[j.start:j.stop]**2).sum() energies = sorted([data_energy, synth_energy]) if energies[1] > max_energy_ratio * energies[0]: if verbose: _log_window_selection( data_trace.id, "Deselecting window due to energy ratio between " "data and synthetics.") continue # Check that amplitudes in the data are above the noise if noise_absolute / data[j.start: j.stop].ptp() > \ max_noise_window: if verbose: _log_window_selection( data_trace.id, "Deselecting window due having no amplitude above the " "signal to noise ratio.") final_windows.append((j.start, j.stop)) if plot: old_time_windows = time_windows.copy() time_windows.mask[:] = True for start, stop in final_windows: time_windows.mask[start:stop] = False if plot: plt.subplot2grid(grid, (30, 0), rowspan=1) _plot_mask(time_windows, old_time_windows, name="LITTLE ENERGY ELIMINATION") if verbose: _log_window_selection( data_trace.id, "Done, Selected %i window(s)" % len(final_windows)) # Final step is to convert the index value windows to actual times. windows = [] for start, stop in final_windows: start = data_starttime + start * data_delta stop = data_starttime + stop * data_delta windows.append((start, stop)) if plot: # Plot the final windows to the data axes. import matplotlib.transforms as mtransforms # NOQA ax = data_plot trans = mtransforms.blended_transform_factory(ax.transData, ax.transAxes) for start, stop in final_windows: ax.fill_between([start * data_delta, stop * data_delta], 0, 1, facecolor="#CDDC39", alpha=0.5, transform=trans) plt.show() return windows
y = np.r_[0:1:0.1, 9:10:0.1] #fig,(ax,ax2) = plt.subplots(1, 2, sharey=True) fig,(ax2,ax) = plt.subplots(2, 1, sharex=True) # plot the same data on both axes ax.plot(x, y, 'bo') ax2.plot(x, y, 'bo') # zoom-in / limit the view to different portions of the data #ax.set_xlim(0,1) # most of the data ax.set_ylim(0,1) # most of the data #ax2.set_xlim(9,10) # outliers only ax2.set_ylim(9,10) # outliers only # hide the spines between ax and ax2 #ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) #ax2.spines['left'].set_visible(False) ax2.spines['bottom'].set_visible(False) ax.yaxis.tick_left() ax.tick_params(labeltop='off') # don't put tick labels at the top #ax2.yaxis.tick_right() ax2.yaxis.tick_left() # Make the spacing between the two axes a bit smaller plt.subplots_adjust(wspace=0.15) plt.show()
noise_scale) theta[t, :] = theta_next.reshape(1, Nosc) phase_dynamics[t, :] = func_oscillator_approx_fourier_series( theta[t, :], K1, K2, omega) for i in range(Nosc): theta_unwrap = np.unwrap(deepcopy(theta[t - 1:t + 1, i])) dtheta[t, i] = (theta_unwrap[1] - theta_unwrap[0]) / h #%% plot phase axis = np.arange(theta.shape[0]) fig = plt.figure(figsize=(20, 8)) gs = fig.add_gridspec(Nosc, 1) plt.subplots_adjust(wspace=0.4, hspace=0.0) for n in range(Nosc): ##################### ax11 = fig.add_subplot(gs[n, 0]) plt.plot(axis, theta[:, n]) plt.ylabel('$\\phi_{%d}$' % (n + 1)) plt.xticks(np.arange(0, Nt + 1, int( Nt / 2))) # plt.xticks(np.arange(0, Nt+1, int(Nt/3))) plt.yticks([0, np.pi, 2 * np.pi], labels=['0', '$\\pi$', '$2 \\pi$']) plt.grid() plt.xlabel('# sample') plt.show()
plt.ylabel("Correlation", fontsize=12) plt.ylim([-0.65, 1.]) plt.yticks([-0.6, -0.4, -0.2, 0., 0.2, 0.4, 0.6, 0.8, 1.], fontsize=12) plt.axhline(y=0., color='k', linestyle='-', linewidth=2.) plt.xlim([-3., 3.]) plt.xlabel("Lag [years]", fontsize=12) return 0 ti = np.arange(-float(t / 12) + 1. / 12, float(t / 12) - 1. / 12., 1. / 12.) fig = plt.figure(figsize=(10, 10)) ax = plt.subplots_adjust(left=0.1, right=0.98, bottom=0.06, top=0.95, hspace=0.35, wspace=0.3) titles = [ "Tropical mean - Low clouds", "Nino3.4 region - Low clouds", "Nino3.4 region - Tropical mean", "Low clouds - Tropical cloud cover" ] for i in range(4): ax = plt.subplot(2, 2, i + 1) plt.title(titles[i]) for j in range(m): plt.plot(t, corr[j, i], 'k', alpha=0.2) plt.plot(t, np.median(corr[:, i], axis=0), 'k', linewidth=2.)
#plt.scatter(z_samples[i,:,0],z_samples[i,:,1]) plt.axis('square'); plt.title('q(z|x={})'.format(y[i])) plt.xlim([xmin,xmax]) plt.ylim([xmin,xmax]) plt.xticks([]) plt.yticks([]); plt.subplot(2,5,5+i+1) plt.contour(xrange, xrange, np.exp(logprior+llh[i]).reshape(300,300).T, cmap='Greens') plt.axis('square'); plt.title('p(z|x={})'.format(y[i])) plt.xlim([xmin,xmax]) plt.ylim([xmin,xmax]) plt.xticks([]) plt.yticks([]); plt.text(-60,20,'KLR Loss: %f, NELBO: %f, KL0: %f, KL1: %f, KL2: %f, KL3: %f, KL4: %f' % (dl, NELBO, KL0, KL1, KL2, KL3, KL4)) plt.text(-28,-7,'KLAVG: %f' %(KLAVG)) plt.savefig('FiguresJCKL\Fig %i'%(j)) plt.close() plt.subplot(2,1,1) plt.plot(KLAVGBRUH) plt.xlabel('Iterations (x100)') plt.ylabel('Avg KL Div') plt.subplot(2,1,2) plt.plot(ISTHISLOSS) plt.xlabel('Iterations (x100)') plt.ylabel('KLR Loss') plt.subplots_adjust(top=0.95,bottom=0.15,right=0.95,hspace=0.4) plt.savefig('FiguresJCKL\Diag Plot', bbox_inches='tight') plt.close()
plt.rc('ytick.minor', width=2.0) plt.rc('lines', markersize=8, markeredgewidth=0.0, linewidth=2.0) #plt.rcParams['ps.fonttype'] = 42 #plt.rcParams['pdf.fonttype'] = 42 fig = plt.figure(num=1, figsize=(9, 7), dpi=600, facecolor='w', edgecolor='k') left = 0.10 # the left side of the subplots of the figure right = 0.94 # the right side of the subplots of the figure bottom = 0.1 # the bottom of the subplots of the figure top = 0.96 # the top of the subplots of the figure wspace = 0.2 # the amount of width reserved for blank space between subplots hspace = 0.0 # the amount of height reserved for white space between subplots plt.subplots_adjust(left=left, bottom=bottom, right=right, top=top, wspace=wspace, hspace=hspace) ax1 = plt.subplot(1, 1, 1) hist = plt.hist( peak_sep_arr_norm, bins=binarr, weights=np.ones(len(peak_sep_arr_norm)) / len(peak_sep_arr_norm), density=False ) #note weights and density arguement make total of y values 1, regardless of bin values plt.xticks(binarr, fontsize=12) plt.yticks(fontsize=12) plt.ylim(0, 0.25) plt.xlabel(r'Period/$\tau_{dyn}^{' + galaxyname + '}$', fontsize=15) plt.ylabel('Fraction of Orbits', fontsize=15)
import numpy as np from scipy.linalg import expm import matplotlib.pylab as plt if __name__ == '__main__': A = np.array([[-1, 1], [0, -1]]) B = np.array([[-1, 5], [0, -2]]) t = np.linspace(0.1, 5, 50) norm_a, norm_b = [], [] for i in t: norm_a.append(np.linalg.norm(expm(A * i))) norm_b.append(np.linalg.norm(expm(B * i))) plt.xkcd() fig = plt.figure() ax = fig.add_subplot(111) plt.subplots_adjust(bottom=0.15, left=0.15) ax.plot(norm_a, 'b') ax.plot(norm_b, 'k') ticks = ax.get_xticks().astype('i') ax.set_xticklabels(ticks, fontsize=16, weight='bold') ticks = ax.get_yticks() ax.set_yticklabels(ticks, fontsize=16, weight='bold') ax.set_xlabel('Time', fontsize=18, weight='bold') ax.set_ylabel(r'$||exp(At)||$', fontsize=18, weight='bold') plt.savefig('spectra.pdf', axis='tight') plt.show()
def display_collision3D(collision, fig=None, ax=None, color_blind=False): if fig is None: fig = plt.figure(figsize=(6, 4), dpi=100) if ax is None: ax = fig.add_subplot(1, 1, 1) ax = fig.gca(projection='3d') plt.subplots_adjust(top=0.98, bottom=0.02, right=0.98, left=0.02) jets, muons, electrons, photons, met = collision lines = draw_beams() if (color_blind == False): pmom = np.array(jets).transpose()[1:4].transpose() origin = np.zeros((len(jets), 3)) lines += draw_jet3D(origin=origin, pmom=pmom) pmom = np.array(muons).transpose()[1:4].transpose() origin = np.zeros((len(muons), 3)) lines += draw_muon3D(origin=origin, pmom=pmom) pmom = np.array(electrons).transpose()[1:4].transpose() origin = np.zeros((len(electrons), 3)) lines += draw_electron3D(origin=origin, pmom=pmom) pmom = np.array(photons).transpose()[1:4].transpose() origin = np.zeros((len(photons), 3)) lines += draw_photon3D(origin=origin, pmom=pmom) if (color_blind == True): pmom = np.array(jets).transpose()[1:4].transpose() origin = np.zeros((len(jets), 3)) lines += draw_jet3D(origin=origin, pmom=pmom, ls='solid', color='gray') pmom = np.array(muons).transpose()[1:4].transpose() origin = np.zeros((len(muons), 3)) lines += draw_muon3D(origin=origin, pmom=pmom, ls='dashed', color='black') pmom = np.array(electrons).transpose()[1:4].transpose() origin = np.zeros((len(electrons), 3)) lines += draw_electron3D(origin=origin, pmom=pmom, ls='dashed', color='gray') pmom = np.array(photons).transpose()[1:4].transpose() origin = np.zeros((len(photons), 3)) lines += draw_photon3D(origin=origin, pmom=pmom, ls='solid', color='black') for l in lines: ax.add_line(l) ax.set_xlim(-200, 200) ax.set_ylim(-200, 200) ax.set_zlim(-200, 200)
def plot_div(self, show=True, save=False): init_div = svf.SpiralVectorField.get_divergence(self.u, self.v) reg_div = svf.SpiralVectorField.get_divergence(self.ur, self.vr) diff = init_div - reg_div plot_extent = [self.x.min(), self.x.max(), self.y.min(), self.y.max()] fig8 = pl.figure(figsize=(self.figW, self.figH)) plot = fig8.add_subplot(1, 3, 1, aspect='equal') im1 = plot.imshow(init_div, vmin=-0.5, vmax=0.5, origin='center', extent=plot_extent, cmap='jet') plot.set_title("Initial Divergence", size=self.text_size, pad=self.title_pad) plot.set_xlim(-5, 5) plot.set_ylim(-5, 5) plot.tick_params(labelsize=self.tick_label_size) cbar = fig8.colorbar(im1, fraction=0.046, pad=0.04) cbar.ax.tick_params(labelsize=self.cbar_label_size) plot = fig8.add_subplot(1, 3, 2, aspect='equal') im2 = plot.imshow(reg_div, vmin=-0.5, vmax=0.5, origin='center', extent=plot_extent, cmap='jet') plot.set_title("GPR Model Divergence", size=self.text_size, pad=self.title_pad) plot.set_xlim(-5, 5) plot.set_ylim(-5, 5) plot.tick_params(labelsize=self.tick_label_size) cbar = fig8.colorbar(im2, fraction=0.046, pad=0.04) cbar.ax.tick_params(labelsize=self.cbar_label_size) plot = fig8.add_subplot(1, 3, 3, aspect='equal') im3 = plot.imshow(diff, vmin=-0.5, vmax=0.5, origin='center', extent=plot_extent, cmap='jet') plot.set_title("Divergence Error", size=self.text_size, pad=self.title_pad) plot.set_xlim(-5, 5) plot.set_ylim(-5, 5) plot.tick_params(labelsize=self.tick_label_size) cbar = fig8.colorbar(im3, fraction=0.046, pad=0.04) cbar.ax.tick_params(labelsize=self.cbar_label_size) pl.subplots_adjust(left=0.06, bottom=0.47, right=0.94, top=0.88, wspace=0.48, hspace=0.0) if show: pl.show() if save: fig8.savefig("divergence.png", dpi=300)
del ode, J, x, ts try: from matplotlib import pylab except ImportError: print("matplotlib not available") raise SystemExit import numpy as np ii = np.asarray([v[0] for v in history]) tt = np.asarray([v[1] for v in history]) xx = np.asarray([v[2] for v in history]) pylab.suptitle('Rober') pylab.subplot(2, 2, 1) pylab.subplots_adjust(wspace=0.3) pylab.semilogy( ii[:-1], np.diff(tt), ) pylab.xlabel('step number') pylab.ylabel('timestep') for i in range(0, 3): pylab.subplot(2, 2, i + 2) pylab.semilogx(tt, xx[:, i], "rgb"[i]) pylab.xlabel('t') pylab.ylabel('x%d' % i) pylab.show()