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


Python pyplot.axhspan函数代码示例

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


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

示例1: runsimplot

	def runsimplot(self):
		"""
		Viz of the MC results
		"""
		
		tdmin = self.iniest.td - 3.0*self.iniest.tderr
		tdmax = self.iniest.td + 3.0*self.iniest.tderr
		
		fig = plt.figure(figsize=(6, 3))
		fig.subplots_adjust(top=0.95, bottom=0.2)
		plt.scatter(self.simtruedelays, self.simmesdelays - self.simtruedelays)
		plt.xlim(tdmin, tdmax)
		plt.xlabel("True delay [day]")
		plt.ylabel("Measurement error [day]")
		plt.axvline(self.iniest.td - self.iniest.tderr, color="gray", linestyle="-", zorder=20)
		plt.axvline(self.iniest.td + self.iniest.tderr, color="gray", linestyle="-", zorder=20)
		plt.axhline(0, color="black", linestyle="-", zorder=20)
		plt.axhline(- self.iniest.tderr, color="gray", linestyle="-", zorder=20)
		plt.axhline(+ self.iniest.tderr, color="gray", linestyle="-", zorder=20)
		plt.axhspan(-self.outest.tderr, self.outest.tderr, xmin=0, xmax=1, lw=0, color="red", alpha=0.2)
		#plt.ylim(- 2.0*self.iniest.tderr, + 2.0*self.iniest.tderr)
		
		
		plt.figtext(0.15, 0.8, "Total/initial error ratio: %.2f" % self.totalratio)
		
		#ax = plt.gca()
		#plt.figtext(0.15, 0.8, "Intrinsic/initial error ratio: %.2f" % self.intrinsicratio)
		#plt.axvline(self.iniest.td - self.iniest.tderr, color="gray", linestyle="-", zorder=20)
		#plt.axvline(self.iniest.td + self.iniest.tderr, color="gray", linestyle="-", zorder=20)
		#plt.axvline(self.outest.td, color="red", linestyle="-", zorder=20)
		
		plt.savefig(os.path.join(self.plotdir, "measvstrue.png"))
		plt.close()
开发者ID:COSMOGRAIL,项目名称:PyCS,代码行数:33,代码来源:run.py

示例2: update

    def update(self, params, pdata, ptype = 'temp'):
        cfg = params['cfg']
        cur_t = params['cur']
        gxsec = params['gxsec']

        self.ax.cla() # this is a brute-force way to update. I don't know how to update errorbar correctly.
        if ptype == 'temp':
            self.ax.axis([cur_t-gxsec, cur_t, cfg['tempmin'], cfg['tempmax']]) # [xmin,xmax,ymin,ymax]
        elif ptype == 'freq':
            self.ax.axis([cur_t-gxsec, cur_t, cfg['freqmin'], cfg['freqmax']]) # [xmin,xmax,ymin,ymax]
            plt.axhspan(cfg["freqnorm"], cfg["freqmax"], facecolor='#eeeeee', alpha=0.5)
        else:
            self.ax.axis([cur_t-gxsec, cur_t, 0, 100]) # [xmin,xmax,ymin,ymax]

        pkgid = 0
        for t in pdata:
            x = t.getlistx()
            y = t.getlisty()
            e = t.getlisto()
            self.ax.plot(x,y,scaley=False,color=params['pkgcolors'][pkgid], label='PKG%d'%pkgid)
            self.ax.errorbar(x,y,yerr=e, lw=.2, color=params['pkgcolors'][pkgid], label = '')
            pkgid += 1

        # we need to update labels everytime because of cla()
        self.ax.set_xlabel('Time [S]')
        if ptype == 'temp':
            self.ax.set_ylabel('Core temperature [C]')
        elif ptype == 'freq':
            self.ax.set_ylabel('Frequency [GHz]')
        else:
            self.ax.set_ylabel('Unknown')
        self.ax.legend(loc='lower left', prop={'size':9})
开发者ID:coolr-hpc,项目名称:pycoolr,代码行数:32,代码来源:clr_matplot_graphs.py

示例3: main

def main():
    """Create age plot"""
    d5_domain = np.linspace(0, 2, 100)

    plt.fill_between(d5_domain, sedov_age(d5_domain, 1, 0.1), sedov_age(d5_domain, 1, 1),
                     label='S-T age, $n_0 \in [0.1, 1]$',
                     color='blue', alpha=0.25)

    plt.fill_between(d5_domain, tau_age(d5_domain, 0.1), tau_age(d5_domain, 1),
                     label=r'$\tau$ age, $f \in [0.1,1]$',
                     color='red', alpha=0.25)

    plt.axhspan(st_time_for_arbitrary_density(1, 1.4, 1.0),
                st_time_for_arbitrary_density(1, 1.4, 0.1),
                color='black', alpha=0.1)
    plt.axhline(st_time_for_arbitrary_density(1, 1.4, 1.0),
                color='black', alpha=0.5)

    # Mej = 1.4 M_sun, i.e. use M_chandrasekhar.
    #plt.semilogy(d5_domain, st_time_with_norm_derived_density(d5_domain, 1, 1.4, 1), color='black', ls=':')


    plt.semilogy(d5_domain, sedov_age(d5_domain, 1, 1), color='blue')
    plt.semilogy(d5_domain, tau_age(d5_domain, 1), color='red')

    plt.xlabel(r'Distance $d_{5}$, scaled to 5 kpc')
    plt.ylabel('Remnant age (yr)')
    plt.ylim(10, 50000)
    plt.legend(loc='lower right', frameon=False)
    plt.tight_layout()
    plt.savefig('ms/fig_age_plot.pdf')
    plt.show()
开发者ID:aarontran,项目名称:g309.2-0.6,代码行数:32,代码来源:age_plot.py

示例4: plplotRaw

def plplotRaw(x, filename):

  filename = filename.split('\t')[0]
  y = []
  xu = unique(x)
  xBin = []
  for valu in xu:
    valb = 0
    for val in x:
      if  valu == val:
        valb +=1
    xBin.append(valb)

  c1 = xu
  c2 = xBin
  F = plt.figure(1)
  h =plt.loglog(c1, c2, 'bo',marker = 'x', markersize=8,markerfacecolor=[1,1,1],markeredgecolor=[0,0,1])

  xr1 = pow(10,floor(log(min(x),10)))
  xr2 = pow(10,ceil(log(min(x),10)))
  yr2 = max(xBin)
 

  plt.axhspan(ymin=0.5,ymax=yr2,xmin=xr1,xmax=xr2)
  plt.ylabel('Pr(X >= x)',fontsize=12);
  plt.xlabel('x',fontsize=12)
  plt.subplots_adjust(left=0.3, bottom=0.3)
  F.set_size_inches(3,2)
  F.savefig('visual/plplot%s.pdf' % filename)
  plt.clf()               
  return h
开发者ID:MoSander,项目名称:mapChEMBLPfam,代码行数:31,代码来源:plplotRaw.py

示例5: plot_daily_schedule

def plot_daily_schedule(df, se, label):
    
    n = se.values()
               
    fig, ax = plt.subplots()

    av_start = []
    av_end = []
    for i in range(len(se)):
        dates = n[i][0]
        t_start = n[i][1]
        t_end = n[i][2]
        # plot date vs. start time
        plt.plot(dates, t_start , 'o', color='#2396D4', alpha=0.5)
        # plot date vs. end time
        plt.plot(dates, t_end, 'o', color='#FF7878', alpha=0.5)
        
        avg_start, std_start = avg_time(t_start)
        avg_end, std_end = avg_time(t_end)
        
        av_start.append(avg_start)
        av_end.append(avg_end)

    total_avg_start, total_std_start = avg_time(av_start)
    total_avg_end, total_std_end = avg_time(av_end)
        
    tmin_start = (total_avg_start - total_std_start).time()   
    tmax_start = (total_avg_start + total_std_start).time() 
    tmin_end = (total_avg_end - total_std_end).time()   
    tmax_end = (total_avg_end + total_std_end).time() 
   
    p = plt.axhspan(tmin_start, tmax_start, fc='#2396D4', ec='#2396D4' , alpha=0.3)
    p = plt.axhspan(tmin_end, tmax_end, fc= '#FF7878', ec='#FF7878', alpha=0.3)
    
    a0 = dt.datetime(1900,1,1,1,0,0)
    dr = [a0 + dt.timedelta(hours=a) for a in range(24) if a%3==0]   
    dr2 = [t.time() for t in dr] 
    
    plt.ylim(dt.datetime(1900,1,1,0,0,0).time(),dt.datetime(1900,1,1,23,59,59).time())
    plt.xticks(rotation=20)
    ax.set_yticks(dr2)
    hfmt = md.DateFormatter('%m.%d')
    ax.xaxis.set_major_formatter(hfmt)
    plt.ylabel('Time of day [hr]')
    plt.title('Daily Work Schedule')
    ax.text(0.02, 0.9, label, transform=ax.transAxes, fontsize=24,
            va='top', ha='left', color='gray')
    plt.xlim(min(df.date)- dt.timedelta(days=4), max(df.date) + dt.timedelta(days=1))
    plt.xlabel('Date')
    plt.text(0.03,0.365, "start work", ha='left', transform=ax.transAxes, 
            color='#1F1AB2', fontsize=12)
    plt.text(0.03,0.675, "leave work", ha='left', transform=ax.transAxes, 
            color='#AB2B52', fontsize=12)
    ax.yaxis.grid(True, linestyle='-', which='major', color='lightgrey',
                      alpha=0.5)
    ax.xaxis.grid(True, linestyle='-', which='major', color='lightgrey',
                      alpha=0.5)
    ax.set_axisbelow(True)
    fig.tight_layout()
    plt.savefig(img_dir+'schedule_'+label.replace(" ",'')+'.png', format="png", dpi=500)
开发者ID:javierahermosa,项目名称:TDC,代码行数:60,代码来源:plots.py

示例6: save

def save(x, K1, K2, R, var1, var2, l, n, normalize, 
        output_dir, save_dat, save_plot):
    out_fname = '%s-%s_l=%d_n=%d'%(var1,var2,l,n)
    if save_dat:
        np.savetxt(os.path.join(output_dir, out_fname+'.dat'), 
            np.vstack((x, K1, K2)).T)
    if save_plot:
        varnames = {'c': r'c', 'c2': r'c^2', 'Gamma1': r'\Gamma_1', 'u': r'u',
                    'rho': r'\rho', 'Y': r'Y', 'psi': r'\psi'}
        plt.axhspan(0, 0, ls='dashed')
        latex = (varnames[var1], varnames[var2])
        plt.plot(x, R*K1, 'r-', label="$RK_{%s,%s}$"%latex)
        plt.plot(x, R*K2, 'b-', label="$RK_{%s,%s}$"%latex[::-1])
        plt.xlabel(r"r/R")
        plt.ylabel(r"$RK^{(n,\ell)}$")
        plt.title(r'Kernel for the $\ell=%d,\;n=%d$ mode'%(l,n))
        plt.legend(loc='upper left')
        #plt.ylim([min(0, min(R*K1), min(R*K2))-0.1,
        #          max(1, max(R*K1), max(R*K2))+0.1])
        plt.ylim([-5, 5])
        if normalize:
            plt.xlim([0, 1.01])
        else:
            plt.xlim([0, max(x)])
        plt.tight_layout()
        plt.savefig(os.path.join(output_dir, out_fname+'.png'))
        plt.close()
开发者ID:earlbellinger,项目名称:asteroseismology,代码行数:27,代码来源:ker_extractor2.py

示例7: plot_cs

def plot_cs(cp, filename=None):
    "cp is a CsParser Object"

    bar_len=10
    bar_gap=5

    if not len(cp.cpus):
        return

    plt.xlabel("time(ns)")
    plt.ylabel("cpu")
    plt.title("context switch chart")

    axd=cp.get_axis()
    plt.axis(axd)

    for cpu in cp.cpus:
        xy=cp.get_cpu_xy(cpu)
        lx, ly = 0, 0
        for x, y in xy:
            if lx != 0:
                plt.axhspan(cpu*3+0.1, (cpu+1)*3-0.1, xmin=float(lx)/float(axd[1]), xmax=float(x)/float(axd[1]), 
                        facecolor=cmap[ly], alpha=0.5)
            lx, ly = x, y

    plt_show(filename)
开发者ID:Kenneth-Lee,项目名称:MyPyUtils,代码行数:26,代码来源:MyPlot.py

示例8: 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

示例9: draw_plot

    def draw_plot(self, x_table, y_table, string_number, sound_name, string_target_frequency):
      
        fig = plt.figure()
        ax = fig.add_subplot(111)

        ax.set_xlabel('t [s]')
        ax.set_ylabel('f [Hz]')
        ax.set_title('Struna '+str((string_number+1))+' do dzwieku '+sound_name)

        plt.plot(x_table, y_table)
        ax.set_xlim(0)
        plt.axhline(y=string_target_frequency)
        plt.axhspan(string_target_frequency-0.7, string_target_frequency+0.7, xmin=0, facecolor='g', alpha=0.5)

        data = ('f0 = '+str(round(y_table[0],2))+' Hz\n'+
                'fk = '+str(round(y_table[len(y_table)-1],2))+' Hz\n'+
                'fz = '+str(round(string_target_frequency,2))+' Hz\n'+
                't = '+str(round(x_table[len(x_table)-1]-x_table[0],2))+' s')
        print data
        ax.text(0.8, 0.01, data,
                verticalalignment='bottom', horizontalalignment='left',
                transform=ax.transAxes,
                fontsize=11)

        plot_name = 'wykres_'+str(string_number)+'.png'
        plt.savefig(os.path.join('/home/pi/Dyplom/', plot_name))                    
        plt.clf()       
开发者ID:zefj,项目名称:guitar-tuning-system,代码行数:27,代码来源:tuner.py

示例10: showav

def showav(d, fig=1, yps=50, btop=100000, bw=2000):
    bins = np.arange(0, btop, bw)
    f = plt.figure(fig)
    plt.clf()
    cnds = dconds(d)
    n = len(cnds)
    yl = 0
    for i, c in enumerate(cnds):
        sp = plt.subplot(1, n, i + 1)
        sp.xaxis.set_visible(False)
        if i > 0:
            sp.yaxis.set_visible(False)
            sp.xaxis.set_visible(False)
        plt.title(c)
        l = len(d[c]['evts'])
        for j in range(l):
            evts = d[c]['evts'][j]
            if evts:
                x = np.array(evts)
                y = np.zeros_like(x) + j
                plt.plot(x, y, marker='.', color='r', linestyle='None')
        z = nhplt(flat(d[c]['evts']), bins, color='r', bottom=l + .2 * yps)
        yl = max(yl, l + 1.3 * yps)
        if d[c]['avgs']:
            z = nhplt(flat(d[c]['avgs']), bins, color='b', bottom=l + .1 * yps)
        if d[c]['dj']:
            for j in range(l):
                evts = d[c]['dj'][j]
                if evts:
                    x = np.array(evts)
                    y = np.zeros_like(x) + j
                    plt.plot(x, y, marker='.', color='g', linestyle='None')
            z = nhplt(flat(d[c]['dj']), bins, color='g', bottom=l + .1 * yps)
        if d[c]['avg'] != None:
            avl = int(l / 2.0)
            if len(d[c]['avg']) == 0:
                plt.axhspan(avl, avl + 1, color='b')
            else:
                x = np.array(d[c]['avg'])
                y = np.zeros_like(x) + avl
                plt.plot(x, y, marker='o', color='b', markersize=10.0, linestyle='None')
                if d[c]['avgvar'] != None:
                    av = d[c]['avgvar']
                    a = [0] + list(x) + [max(flat(d[c]['evts']))]
                    nx = [(a[i] + a[i - 1]) / 2.0 for i in range(1, len(a))]
                    ny = np.zeros_like(nx) + avl
                    ye = ([0] * len(av), [v[4] * yps for v in av])
                    plt.errorbar(nx, ny, yerr=ye, color='k', marker='.',
                                 markersize=4.0, linestyle='None', elinewidth=3)
                    av = av[:-1]
                    xmc = np.array([v[1] for v in av])
                    xe = [v[2] for v in av]
                    ymc = np.array([v[3] * yps for v in av])
                    plt.errorbar(x + xmc, y + ymc, xerr=xe, marker='s', color='b',
                                 markersize=6.0, linestyle='None', elinewidth=3)
    for i in range(len(cnds)):
        sp = plt.subplot(1, n, i + 1)
        plt.ylim([0, yl])
    f.canvas.draw()
开发者ID:gic888,项目名称:gdblocks,代码行数:59,代码来源:rdj.py

示例11: plotAvgHist

def plotAvgHist(column, field, bins=40):
    global subplot
    subplot +=1
    plt.subplot(subplot)
    plt.title( '%s: \nmean=%s std=%s ' % (field, round(mean(column), 3), round(std(column), 3)), fontsize=11 )
    plt.axhspan(0, 2000, color='none')
    plt.hist( column, bins=bins, range=(0,1))
    print '%s: mean=%s std=%s items_under_0.3=%s' % (field, round(mean(column), 3), round(std(column), 3), sum([1 for c in column if c<0.3]) )
开发者ID:jamendo,项目名称:jamendo-ratings-sdk,代码行数:8,代码来源:reviewAVGs.py

示例12: plot_graph

def plot_graph():
    """
    Plots a graph with specs listed below
    :return: a nice matplotlib graph
    """
    # sets the parametres of the graph to be plotted
    fig, ax = plt.subplots()

    # Plots the actual graph out of the above lists
    stock_line = plt.plot(datetime_list,
                          monthly_prices,
                          color='#33CCFF',
                          linewidth=3.0,
                          linestyle='-')
    # Demarcates the fields of best and worst performing months
    plt.axhspan(ymin=min(best_stock_prices),
                ymax=max(best_stock_prices),
                xmin=0,
                xmax=1,
                color='#99CC00')
    green_best = mpatches.Patch(color='#99CC00')
    plt.axhspan(ymin=min(worst_stock_prices),
                ymax=max(worst_stock_prices),
                xmin=0,
                xmax=1,
                color='#FF0066')
    red_worst = mpatches.Patch(color='#FF0066')

    # all the labelling, ticks based on dates, and some style stuff
    ax.set_title(stock_title + '\nHistorical Monthly Prices')
    ax.spines["right"].set_visible(False)
    ax.spines["top"].set_visible(False)
    ax.set_ylabel("$\$$ USD")
    ax.xaxis.set_major_locator(years)
    ax.xaxis.set_major_formatter(yearsFmt)
    ax.xaxis.set_minor_locator(months)

    # makes sure the x axis is is as long as the data
    datemin = min(datetime_list)
    datemax = max(datetime_list)
    ax.set_xlim(datemin, datemax)
    box = ax.get_position()
    ax.set_position([box.x0, box.y0 + box.height * 0.1,
                     box.width, box.height * 0.9])

    # Put a legend below current axis
    ax.legend([green_best, red_worst], ['Best Months', 'Worst Months'],
              loc=9, bbox_to_anchor=(0.5, -0.1), ncol=3)

    # sets the display parametres for mouseover (x = time, y = price)
    def price(x): return '$%1.2f'% x
    ax.format_xdata = mdates.DateFormatter('%Y/%m')
    ax.format_ydata = price
    ax.grid(True)

    fig.autofmt_xdate()
    fig.savefig('bonus_02_visual.png')
    plt.show()
开发者ID:tabris1103,项目名称:inf1340_2014_asst3,代码行数:58,代码来源:bonus_02_visual.py

示例13: plot_scatter

def plot_scatter(table, labels, k):
  markers = ['o', 'x', '^', '*', 's']

  print len(table), len(labels)

  tab = np.column_stack((np.array(table), np.array(labels)))
#  np.random.shuffle(tab)
#  tab = tab[:50000]
#  plt.ioff()
#
#  plt.plot(tab[:,0], tab[:,1], markers[0])
#  
#
#  y1 = sorted([x[1] for x in tab if x[0] < 0.5])
#  y2 = sorted([x[1] for x in tab if x[0] >= 0.5])
# 
#  n = len(y1)
#  
#  plt.axhspan(0, y2[n/3], 0.5, 1, hold=None, fill=False)
#  plt.axhspan(y2[n/3], y2[2*n/3], 0.5, 1, hold=None, fill=False)
#  plt.axhspan(y2[2*n/3], 1.0, 0.5, 1, hold=None, fill=False)
#  
#  plt.axhspan(0, y1[n/3], 0, 0.5, hold=None, fill=False)
#  plt.axhspan(y1[n/3], y1[2*n/3], 0, 0.5, hold=None, fill=False)
#  plt.axhspan(y1[2*n/3], 1.0, 0, 0.5, hold=None, fill=False)
#  
#



#  for x in range(l):
#    for y in range(w):
#      plt.axhspan(y*1.0/w, (y+1.0)/w, (x*1.0)/l, (x+1.0)/l, hold=None, fill=False)


   
  for it in range(k):
    sub_tab = np.array([np.array(row) for row in tab if int(row[-1]) == int(it)])
    plt.plot(sub_tab[:,0], sub_tab[:,1], markers[it%5])
    xmin = 2
    ymin = 2
    xmax = -1
    ymax = -1

    for row in sub_tab:
      if row[0] < xmin:
        xmin = row[0]
      if row[0] > xmax:
        xmax = row[0]
      if row[1] < ymin:
        ymin = row[1]
      if row[1] > ymax:
        ymax = row[1]
    
    plt.axhspan(ymin, ymax, xmin, xmax, hold=None, fill=False)

  plt.show()
开发者ID:chouxiaowen,项目名称:queryopt,代码行数:57,代码来源:plot.py

示例14: plot_palette

def plot_palette(pa, title=None, xlabel=None, y=None, show_regions=False, show_primary_haps=False,
                 pair_gap=0, linewidth=6, snp_range=None, colors=None):
    '''Generate a haplotype coloring plot from coloring palette pa.'''
    # Generate haplotype colors 
    haps, regions, c = pa.haps, pa.regions, pa.color
    
    colors = colors if colors is not None else list(it.islice(im.plot.colors.get_colors(), pa.num_colors))
    # Last color: always gray
    colors[-1] = (0.4, 0.4, 0.4)

    # Prepare axes
    num_haps = len(haps)
    y = y if y is not None else map(repr, haps)
    xmin, xmax = regions[0][START], regions[-1][STOP]
    x_scaled = lambda x: (1.0 * (x - xmin)) / (xmax - xmin)
    
    P.clf()
    P.hold(True)
    if title is not None: P.title(title)
    P.xlim([xmin, xmax])
    P.xlabel(xlabel if xlabel else 'SNP #')
    P.ylabel('Sample')
    hap_ticks = np.arange(0, num_haps)
    if pair_gap > 0:
        hap_ticks += np.array(list(it.chain.from_iterable(map(lambda x: (x, x), xrange(num_haps / 2)))))
    P.yticks(hap_ticks, y)
    ymin, ymax = hap_ticks[0] - 0.5, hap_ticks[-1] + 0.5
    P.ylim([ymin, ymax])

    # Show region boundaries in dashed lines
    if show_regions:
        boundaries = sorted(set([y for x in pa.regions for y in x]))
        print boundaries
        for k, boundary in enumerate(boundaries[1:], 1):
            P.axvline(x=boundary, linestyle='dotted', linewidth=1, color='k')
            P.text(0.5 * (boundaries[k - 1] + boundaries[k]), hap_ticks[0] - 0.4, '%d' % (k - 1,))
            
    # Draw each segment in its corresponding color
    for i, j in it.product(xrange(pa.num_haps), xrange(pa.num_regions)):
        # Draw lines for all members of the group using the same color
        # print '[%d,%d] x %.2f:%.2f y=%.2f color %d' % (regions[j][START], regions[j][STOP], x_scaled(regions[j][START]), x_scaled(regions[j][STOP]), hap_ticks[i], c[i, j])
        P.axhspan(xmin=x_scaled(regions[j][START]), xmax=x_scaled(regions[j][STOP]),
                  ymin=hap_ticks[i] - 0.5 * linewidth, ymax=hap_ticks[i] + 0.5 * linewidth,
                  color=colors[c[i, j]])
    
    # Draw where primary haplotypes have been identified
    if show_primary_haps:
        primary = pa.color_sequence()
        for k, seq in enumerate(primary): 
            for i, j in seq:
                P.axhspan(xmin=x_scaled(regions[j][START]), xmax=x_scaled(regions[j][STOP]),
                          ymin=hap_ticks[i] + 0.9 * linewidth, ymax=hap_ticks[i] + 1.1 * linewidth,
                          color=colors[k])
    P.show()
开发者ID:orenlivne,项目名称:ober,代码行数:54,代码来源:hap_color.py

示例15: plot

 def plot(self, win=None, newfig=True, figsize=None, orientation='hor', topfigfrac=0.8):
     """Plot layout
     
     Parameters
     ----------
 
     win : list or tuple
         [x1, x2, y1, y2]
         
     """
     
     if newfig:
         plt.figure(figsize=figsize)
         ax1 = None
         ax2 = None
         if orientation == 'both':
             ax1 = plt.axes([0.125, 0.18 + (1 - topfigfrac) * 0.7, (0.9 - 0.125), topfigfrac * 0.7])
             ax2 = plt.axes([0.125, 0.11, (0.9 - 0.125), (1 - topfigfrac) * 0.7], sharex=ax1)
         elif orientation[:3] == 'hor':
             ax1 = plt.subplot()
         elif orientation[:3] == 'ver':
             ax2 = plt.subplot()
     else:
         if orientation == 'both':
             fig = plt.gcf()
             ax1 = fig.axes[0]
             ax2 = fig.axes[1]
         elif orientation[:3] == 'hor':
             fig = plt.gcf()
             ax1 = fig.axes[0]
             ax2 = None
         elif orientation[:3] == 'ver':
             fig = plt.gcf()
             ax1 = None
             ax2 = fig.axes[0]
     if ax1 is not None:
         plt.sca(ax1)
         for e in self.elementlist:
             e.plot()
         if orientation[:3] == 'hor':
             plt.axis('scaled')
         elif orientation == 'both':
             plt.axis('equal')  # cannot be 'scaled' when sharing axes
         if win is not None:
             plt.axis(win)
     if ax2 is not None:
         plt.sca(ax2)
         for i in range(self.aq.nlayers):
             if self.aq.ltype[i] == 'l':
                 plt.axhspan(ymin=self.aq.z[i + 1], ymax=self.aq.z[i], color=[0.8, 0.8, 0.8])
         for i in range(1, self.aq.nlayers):
             if self.aq.ltype[i] == 'a' and self.aq.ltype[i - 1] == 'a':
                 plt.axhspan(ymin=self.aq.z[i], ymax=self.aq.z[i], color=[0.8, 0.8, 0.8])
开发者ID:jentjr,项目名称:timml,代码行数:53,代码来源:util.py


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