当前位置: 首页>>代码示例>>Python>>正文


Python pyplot.axvspan函数代码示例

本文整理汇总了Python中matplotlib.pyplot.axvspan函数的典型用法代码示例。如果您正苦于以下问题:Python axvspan函数的具体用法?Python axvspan怎么用?Python axvspan使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了axvspan函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: ScatterPlot

def ScatterPlot(TransitionForces,ListOfSepAndFits,ExpectedContourLength,
                OutDir):
    """
    Makes a scatter plot of the contour length and transition forces

    Args:
        TransitionForces: array, each element the transition region for curve i
        ListOfSepAndFits: array, each element the output of GetWLCFits
        ExpectedContourLength: how long we expect the construct to be
        OutDir: base directory, for saving stuff
    """
    L0Arr = []
    TxArr = []
    for (SepNear,FitObj),TransitionFoces in zip(ListOfSepAndFits,
                                                TransitionForces):
        MedianTx = np.median(TransitionFoces)
        L0,Lp,_,_ = FitObj.Params()
        L0Arr.append(L0)
        TxArr.append(MedianTx)
    # go ahead an throw out ridiculous data from the WLC, where transition
    # normalize the contour length to L0
    L0Arr = np.array(L0Arr)/ExpectedContourLength
    # convert to useful units
    L0Plot = np.array(L0Arr)
    TxPlot =  np.array(TxArr) * 1e12
    fig = pPlotUtil.figure(figsize=(12,12))
    plt.subplot(2,2,1)
    plt.plot(L0Plot,TxPlot,'go',label="Data")
    alpha = 0.3
    ColorForce = 'r'
    ColorLength = 'b'
    plt.axhspan(62,68,color=ColorForce,label=r"$F_{\rm tx}$ $\pm$ 5%",
                alpha=alpha)
    L0BoxMin = 0.9
    L0BoxMax = 1.1
    plt.axvspan(L0BoxMin,L0BoxMax,color=ColorLength,
                label=r"L$_{\rm 0}$ $\pm$ 10%",alpha=alpha)
    fudge = 1.05
    # make the plot boundaries OK
    MaxX = max(L0BoxMax,max(L0Plot))*fudge
    MaxY = 90
    plt.xlim([0,MaxX])
    plt.ylim([0,MaxY])
    pPlotUtil.lazyLabel("",r"F$_{\rm overstretch}$ (pN)",
                        "DNA Characterization Histograms ",frameon=True)
    ## now make 1-D histograms of everything
    # subplot of histogram of transition force
    HistOpts = dict(alpha=alpha,linewidth=0)
    plt.subplot(2,2,2)
    TransitionForceBins = np.linspace(0,MaxY)
    plt.hist(TxPlot,bins=TransitionForceBins,orientation="horizontal",
             color=ColorForce,**HistOpts)
    pPlotUtil.lazyLabel("Count","","")
    plt.ylim([0,MaxY])
    plt.subplot(2,2,3)
    ContourBins = np.linspace(0,MaxX)
    plt.hist(L0Plot,bins=ContourBins,color=ColorLength,**HistOpts)
    pPlotUtil.lazyLabel(r"$\frac{L_{\rm WLC}}{L_0}$","Count","")
    plt.xlim([0,MaxX])
    pPlotUtil.savefig(fig,"{:s}Out/ScatterL0vsFTx.png".format(OutDir))
开发者ID:prheenan,项目名称:Research,代码行数:60,代码来源:MainCorrection.py

示例2: output_spectrum

def output_spectrum(wl, vec, interval=None):
  order = np.argsort(wl)
  p = plt.plot(wl[order], vec[order], color='red')
  ax = plt.gca()
  ax.set_xlabel('Wavelength')
  ax.set_ylabel('Magnitude')
  ax.grid(True)
  ax.spines['bottom'].set_color('white')
  ax.spines['top'].set_color('white')
  ax.spines['left'].set_color('white')
  ax.spines['right'].set_color('white')
  ax.xaxis.label.set_color('white')
  ax.yaxis.label.set_color('white')
  ax.tick_params(axis='x', colors='white')
  ax.tick_params(axis='y', colors='white')
  if interval is not None:
      plt.axvspan(interval[0], interval[1], facecolor='white', alpha=0.25)
  plt.savefig('spectrum_out.png',transparent=True)
  sys.stdout.write('%i'%len(wl))
  for w in wl:
    sys.stdout.write(' %f' % w)
  for v in vec:
    sys.stdout.write(' %f' % v)
  sys.stdout.write('\n')
  os.system('convert -resize 100x100 spectrum_out.png thumb_out.png')
开发者ID:davidraythompson,项目名称:hsifind,代码行数:25,代码来源:hsifind.py

示例3: plot_trade_windows

 def plot_trade_windows(self, dt_s, dt_e, f_width):
     ts_signal = self.getBollingerValue(dt_s, dt_e)
     dt_previous = ''
     s_color_previous = ''
     
     for i in range(len(ts_signal)):
         # get values for the current date
         dt = ts_signal.index[i]
         s = ts_signal[dt]
         s_color = 'r' if s >= f_width else 'g' if s <= -f_width else ''
                         
         # update the figure: on change and in last day
         if s_color != s_color_previous \
         or (i == len(ts_signal)-1):
             
             # if we are ending a trade opportunity window
             if s_color_previous != '':
                 # shade the trade opportunity window
                 plt.axvspan(dt_previous, dt, color=s_color_previous, alpha=0.25)
                 
                 # draw the end line
                 plt.axvline(x=dt, color=s_color_previous, alpha=0.5)
             
             # if we are starting a new trade opportunity window
             if s_color != '':
                 # draw the start line
                 plt.axvline(x=dt, color=s_color, alpha=0.5)
             
             # save the last event
             s_color_previous = s_color
             dt_previous = dt
开发者ID:adsar,项目名称:repo01,代码行数:31,代码来源:TechnicalAnalysis.py

示例4: _periodogram_plot

def _periodogram_plot(title, column, data, trend, peaks):
    """display periodogram results using matplotlib"""

    periods, power = periodogram(data)
    plt.figure(1)
    plt.subplot(311)
    plt.title(title)
    plt.plot(data, label=column)
    if trend is not None:
        plt.plot(trend, linewidth=3, label="broad trend")
        plt.legend()
        plt.subplot(312)
        plt.title("detrended")
        plt.plot(data - trend)
    else:
        plt.legend()
        plt.subplot(312)
        plt.title("(no detrending specified)")
    plt.subplot(313)
    plt.title("periodogram")
    plt.stem(periods, power)
    for peak in peaks:
        period, score, pmin, pmax = peak
        plt.axvline(period, linestyle='dashed', linewidth=2)
        plt.axvspan(pmin, pmax, alpha=0.2, color='b')
        plt.annotate("{}".format(period), (period, score * 0.8))
        plt.annotate("{}...{}".format(pmin, pmax), (pmin, score * 0.5))
    plt.tight_layout()
    plt.show()
开发者ID:Lampadina,项目名称:seasonal,代码行数:29,代码来源:application.py

示例5: plot_frag_arrays

def plot_frag_arrays(conditions, transcript_arrays, outputdir, transcript_coords, transcripts_dict, paired):
	#Plot sererately per transcript
	for transcript in sorted(transcripts_dict): #Key is transcript, values are dict of positions and then fragments 
		a = 1
		for frag_pos in sorted(transcripts_dict[transcript]):
			c = 1
			for sample in sorted(transcript_arrays[transcript]):
				length_of_transcript = len(transcript_arrays[transcript][sample])
				base_label = np.array(xrange(length_of_transcript))

				c += 1 #Count number of samples for legend size	
				plt.plot(base_label, transcript_arrays[transcript][sample], label="{}".format(sample)) #Same as transcripts
			
			start_pos = int(frag_pos[1]) - int(transcript_coords[transcript][1])
			end_pos = int(frag_pos[2]) - int(transcript_coords[transcript][1])
			plt.axvspan(start_pos, end_pos, color='red', alpha=0.2)
			if paired:
				start_pos = int(frag_pos[3]) - int(transcript_coords[transcript][1])
				end_pos = int(frag_pos[4]) - int(transcript_coords[transcript][1])
				plt.axvspan(start_pos, end_pos, color='red', alpha=0.2)
		#Plot labels
			if c <= 4: #Control size of legend
				plt.legend(bbox_to_anchor=(1.05, 1), loc=1, borderaxespad=0., prop={'size':5})
			else:
				plt.legend(bbox_to_anchor=(1.05, 1), loc=1, borderaxespad=0., prop={'size':7})
			plt.ylabel('Read Count')
			plt.savefig(outputdir+'/plots/{}_{}.png'.format(transcript, a))
			plt.close()
			a += 1
开发者ID:pdl30,项目名称:pynoncode,代码行数:29,代码来源:plot.py

示例6: draw_shannon_distrib

def draw_shannon_distrib(neut_h, obs_h, outfile=None, filetype=None,
                         size=(15, 15)):
    '''
    draws distribution of Shannon values for random neutral

    :argument neut_h: list of Shannon entropies corresponding to simulation under neutral model
    :argument obs_h: Shannon entropy of observed distribution of abundance
    :argument None outfile: path were image will be saved, if none, plot
       will be shown using matplotlib GUI
    :argument None filetype: pdf or png
    :argument (15,15) size: size in inches of the drawing
    
    '''
    neut_h = np.array ([float (x) for x in neut_h])
    obs_h = float (obs_h)
    pyplot.hist(neut_h, 40, color='green', histtype='bar', fill=True)
    pyplot.axvline(float(obs_h), 0, color='r', linestyle='dashed')
    pyplot.axvspan (float(obs_h) - neut_h.std(), float(obs_h) + neut_h.std(),
                    facecolor='orange', alpha=0.3)
    pyplot.xlabel('Shannon entropy (H)')
    pyplot.ylabel('Number of observations over %s simulations' % (len (neut_h)))
    pyplot.title("Histogram of entropies from %s simulations compared to \nobserved entropy (red), deviation computed from simulation" % (len (neut_h)))
    fig = pyplot.gcf()
    dpi = fig.get_dpi()
    fig.set_size_inches (size)
    if outfile:
        fig.savefig(outfile, dpi=dpi+30, filetype=filetype)
        pyplot.close()
    else:
        pyplot.show()
开发者ID:fransua,项目名称:ecolopy,代码行数:30,代码来源:utils.py

示例7: plot

def plot(rr_file, tag_file):
    """
    Paint results of acquisition
    @param rr_file: Path to file that contains rr values
    @param tag_file: Path to file that contains tag values
    """

    import matplotlib.pyplot as plt
    plt.switch_backend("WXAgg")

    colors = ['orange', 'green', 'lightblue', 'grey', 'brown', 'red', 'yellow', 'black', 'magenta', 'purple']
    shuffle(colors)
    rr_values = parse_rr_file(rr_file)
    hr_values = map(lambda rr: 60 / (float(rr) / 1000), rr_values)
    tag_values = parse_tag_file(tag_file)
    x = [x / 1000 for x in cumsum(rr_values)]
    y = hr_values
    plt.plot(x, y)

    for tag in tag_values:
        c = colors.pop()
        plt.axvspan(tag[0], tag[0] + tag[2], facecolor=c, alpha=.8, label=tag[1])

    plt.ylabel('Heart rate (bpm)')
    plt.xlabel('Time (s)')
    plt.title('Acquisition results')
    plt.ylim(ymin=min(min(y) - 10, 40), ymax=max(max(y) + 10, 150))
    plt.legend()
    plt.show()
开发者ID:Tavpritesh,项目名称:gVarvi,代码行数:29,代码来源:utils.py

示例8: fig_nucleotide_gene

 def fig_nucleotide_gene(self):
     print '# Plotting gene in nucleotide resolution.'
     fig = plt.figure(figsize=(15, 10), dpi=80, facecolor='w', edgecolor='k')
     if len(self.experiments) > 1:
         print 'More than one experiment. Preprocess concat file to get only one experiment:' \
               "cat your.concat | awk '$7 == \"experiment\" {print $0}' > experiment.concat"
         exit()
     else:
         e = self.experiments[0]
         fig_no, plot_no = 0, 0
         for i_gene_id in self.genes_id_list:
             gene_name = self.id_to_names[i_gene_id]
             plot_no += 1
             ax = fig.add_subplot(5, 1, plot_no)
             fig.tight_layout()
             plt.title(e)
             ax.set_ylabel("no. of reads")
             ax.set_xlabel('ID: '+i_gene_id+', Name: '+gene_name)
             try:
                 self.data[gene_name][e] = self.data[gene_name][e][self.three_prime_flank:-self.three_prime_flank:] # plot only gene
                 bar = ax.bar(self.data[gene_name][e]['position'], self.data[gene_name][e]['hits'], width=0.5)
                 for i in self.genes[gene_name]['exons']:
                     plt.axvspan(i[0], i[1], alpha=0.2, color='orange')
                 plt.xticks(list(self.data[gene_name][e]['position']), list(self.data[gene_name][e]['nucleotides']), fontsize=8)
             except KeyError:
                 plt.text(0.5,0.5,"NO READS")
             if plot_no == 5:
                 fig_no += 1
                 plt.savefig(self.prefix+'nuc_gene'+'_l'+str(self.lookahead)+'_t'+str(self.hits_threshold)+'_'+'_fig_'+str(fig_no)+'.png')
                 plt.clf()
                 plot_no = 0
         if plot_no > 0:
             plt.savefig(self.prefix+'nuc_gene'+'_l'+str(self.lookahead)+'_t'+str(self.hits_threshold)+'_'+'_fig_'+str(fig_no+1)+'.png')
             plt.clf()
     return True
开发者ID:tturowski,项目名称:gwide,代码行数:35,代码来源:otherPol3FromConcat.py

示例9: day_e_plot

def day_e_plot(results, plot_date, save):

    import matplotlib.pyplot as plt

    fig = plt.figure()

    results['USAGE'].ix[plot_date].plot(linestyle='--', linewidth=5, color=darkgray)

    results['grid_demand_peak'].ix[plot_date].plot(marker='', linestyle='-', linewidth=2, color=redorange)
    results['grid_demand_offpeak'].ix[plot_date].plot(marker='', linestyle='-', linewidth=2, color=purple)
    results['grid_store'].ix[plot_date].plot(marker='', linestyle='-', linewidth=2, color=mint)
    results['storage_available'].ix[plot_date].plot(marker='', linestyle='-', linewidth=2, color=apple)
    results['storage_send'].ix[plot_date].plot(marker='', linestyle='-', linewidth=2, color=navy, grid='off')

    plt.axvspan(plot_date+' 10:00:00',plot_date+' 19:00:00', facecolor=lightgray, alpha=0.5)

    plt.legend(['Demand',
                'Peak Grid for Demand',
                'Off-Peak Grid for Demand',
                'Grid to Battery',
                'Storage Available',
                'Storage to Demand'],
               labelspacing=.2,
               prop={'size':10})

    plt.title('Demand-Side Storage Model, Hourly Energy State \n %s' %plot_date)
    plt.ylabel('Hourly Electricity State (kWh)', fontsize=14)

    if save == True:

        filename = 'Daily_Energy_State_'+plot_date+'.png'

        plt.savefig(filename)

    plt.show()
开发者ID:rinckd,项目名称:demandside_storage,代码行数:35,代码来源:storage_analysis.py

示例10: plot_timeseries_comparison

def plot_timeseries_comparison(masked, inf):
    fig = plt.figure(figsize=(16,4))

    times = np.arange(len(masked))*inf.dt
    warnings.warn("Only plotting every 10th point of time series.")
    plt.plot(times[::10], masked.data[::10], 'k-', drawstyle='steps-post', 
             label='Time series', zorder=1)

    inverted = invert_mask(masked) 
    slices = np.ma.flatnotmasked_contiguous(inverted)
    if slices:
        for ii, badslice in enumerate(slices):
            if ii == 0:
                label='Radar indentified'
            else:
                label="_nolabel"
            tstart = inf.dt*(badslice.start)
            tstop = inf.dt*(badslice.stop-1)
            plt.axvspan(tstart, tstop, alpha=0.5, 
                        fc='r', ec='none', zorder=0, label=label)
    
    plt.figtext(0.02, 0.02,
                "Frac. of data masked: %.2f %%" % ((len(masked)-masked.count())/float(len(masked))*100), 
                size='x-small')
    plt.figtext(0.02, 0.05, inf.basenm, size='x-small')

    plt.xlabel("Time (s)")
    plt.ylabel("Intensity")
    plt.xlim(0, times.max()+inf.dt)

    plt.subplots_adjust(bottom=0.15, left=0.075, right=0.98)
开发者ID:chitrangpatel,项目名称:radar-removal,代码行数:31,代码来源:find_radar_mod.py

示例11: colorize_phases

def colorize_phases(STOP_TIME,durrationOfStep,ev_foot_const):
    for phase in range(int(1+STOP_TIME/durrationOfStep)):
        t0_phase = phase*durrationOfStep
        t1_phase = (phase+ev_foot_const)*durrationOfStep
        t2_phase = (phase+1)*durrationOfStep
        plt.axvspan(t0_phase, t1_phase, color='g', alpha=0.3, lw=2) #adaptative part (foot goal can change)
        plt.axvspan(t1_phase, t2_phase, color='r', alpha=0.3, lw=2) #non adaptative part
开发者ID:thomasfla,项目名称:minimal-pg,代码行数:7,代码来源:macro_plot.py

示例12: snap1

def snap1(vector):
	fig = plt.figure()
	plt.plot(vector)
	plt.axvspan(75, 125, facecolor='b', alpha=0.3)
	plt.xlabel('$x$')
	plt.ylabel('$Ez$')
	plt.show()
开发者ID:kewitz,项目名称:YeeCUDA,代码行数:7,代码来源:bench.py

示例13: plotRegion

def plotRegion(start,end,area,bpScores,centers):
	if len(centers) < 6 or len(area) < 2000:
		return
	
	plt.clf()
	
	left=len(area)/2-1000
	right=len(area)/2+1000
	
	smooth=[]
	for i in range(len(area)):
		smooth.append(sum(area[max(0,i-10):i+10])/20.)
	print smooth
	print centers
	for center in centers:
		#plt.axvline(center[0]-start-74, color="gray")
		#plt.axvline(center[0]-start+74, color="gray")
		plt.axvspan(center[0]-73, center[0]+73, color='gray', alpha=0.3)
		plt.axvline(center[0], color="black")
	plt.plot(smooth)
	plt.plot(bpScores,"red")
	plt.title("Smoothed Read Start Count (chr21:"+str(start+left)+"-"+str(start+right)+")")
	plt.xlabel("Relative BP position")
	plt.ylabel("Count or Score")
	plt.xlim([left,right])
	plt.ylim([0,10])
	fig = matplotlib.pyplot.gcf()
	fig.set_size_inches(16,2)
	plt.savefig(sys.argv[3]+"_"+str(start)+"-"+str(end)+'.plot.pdf', dpi=100)
开发者ID:AllanSSX,项目名称:sanefalcon,代码行数:29,代码来源:nuclDetector.py

示例14: plot_y_dist

def plot_y_dist(y_train, y_test):

    """
    Plotting the counts of inhibition scores
    :param y_train: Target values used for training
    :param y_test: Target values used for testing
    :return: None
    """

    y_train = pd.read_csv('https://s3-us-west-2.amazonaws.com/pphilip-usp-inhibition/'
                          'data/y_train_postprocessing.csv')
    y_test = pd.read_csv('https://s3-us-west-2.amazonaws.com/pphilip-usp-inhibition/'
                         'data/y_test_postprocessing.csv')
    y_train.columns = ['ID', 'Activity_Score']
    df_train = y_train.groupby('Activity_Score')['ID'].nunique().to_frame()
    df_train['score'] = df_train.index
    df_train.columns = ['score_counts', 'score']
    df_train = df_train.reset_index(drop=True)

    y_test.columns = ['ID', 'Activity_Score']
    df_test = y_test.groupby('Activity_Score')['ID'].nunique().to_frame()
    df_test['score'] = df_test.index
    df_test.columns = ['score_counts', 'score']
    df_test = df_test.reset_index(drop=True)
    plt.plot(df_train['score'], df_train['score_counts'])
    plt.plot(df_test['score'], df_test['score_counts'])
    plt.title('Sample counts of unique inhibition scores')
    plt.xlabel('Inhibition score')
    plt.ylabel('Number of molecule samples')
    plt.axvspan(0, 40, facecolor='orange', alpha=0.2)
    plt.axvspan(40, 100, facecolor='violet', alpha=0.2)
    plt.savefig('./plots/score_counts.png', bbox_inches='tight')
开发者ID:pearlphilip,项目名称:USP-inhibition,代码行数:32,代码来源:plots.py

示例15: showdata

def showdata(f, info):
    print(repr(info))
    offA, offB = info
    offMin, offMax = min(info), max(info)
    
    offMax += 11*EODSamples*BytesPerSample
    offMin -= 10*EODSamples*BytesPerSample
    offMin = max(0, offMin)
    rlen = offMax - offMin
    
    posA = (offA-offMin) / BytesPerSample
    posB = (offB-offMin) / BytesPerSample    
    
    f.seek(offMin)
    data = f.read(rlen)
    arr = np.frombuffer(data, dtype=np.float32)
   
    plt.figure(1,figsize=(24,14))
    plt.clf()
    ax = None
    for ch in xrange(NumChannels):
        charr = arr[ch::NumChannels]
        if ch == 0:
            ax = plt.subplot(NumChannels, 1, 1)
        else:
            plt.subplot(NumChannels, 1, ch+1, sharex=ax)
        plt.plot(charr,'k')
        plt.axvspan(posA, posA + EODSamples, fc='r', ec='r', alpha=.5)
        plt.axvspan(posB, posB + EODSamples, fc='g', ec='g', alpha=.5)
        plt.axis([0, len(charr), -10, 10])
        plt.ylabel('ch%d'%ch)
        
    plt.show()
开发者ID:neurobiofisica,项目名称:gymnotools,代码行数:33,代码来源:singlefishviewer.py


注:本文中的matplotlib.pyplot.axvspan函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。