• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python pyplot.axhspan函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: main

def main():
    z = np.arange(-7, 7, 0.1)
    phi_z = sigmoid(z)
    plt.plot(z, phi_z)
    plt.axvline(0.0, color='k')
    plt.axhspan(0.0, 1.0, facecolor='1.0', alpha=1.0, ls='dotted')
    plt.axhline(y=0.5, ls='dotted', color='k')
    plt.yticks([0.0, 0.5, 1.0])
    plt.ylim(-0.1, 1.1)
    plt.xlabel('z')
    plt.ylabel('$\phi (z)$')
    plt.show()
开发者ID:ilikesongdandan,项目名称:Introduction-to-Programming-Using-Python,代码行数:12,代码来源:sigmoid_demo.py


示例17: plot_2D

    def plot_2D(self, file_name, var1, var2, nbins1, nbins2, xmin1, xmax1,
                xmin2, xmax2, **kwargs):
        vals1 = []
        wgts = []
        vals2 = []

        cuts = kwargs.get('cuts', '(True)')
        title = kwargs.get('title', '')
        xlab = kwargs.get('xlab','')
        ylab = kwargs.get('ylab','')

        cut = "%s & %s" % (self.base_selections, cuts)

        for mc in self.sample_order:

            self.log.info("Processing MC: %s" % mc)

            for sample_name in self.sample_groups[mc]["sample_names"]:
                with tb.open_file("%s/%s.h5" % (self.ntuple_dir, sample_name),
                        'r') as h5file:
                    for chan in self.channels:
                        table = getattr(getattr(h5file.root, self.analysis),
                                        chan)
                        vals1 += [x[var1] for x in table.where(cut)]
                        vals2 += [x[var2] for x in table.where(cut)]
                        scale = self.lumi * xsec.xsecs[sample_name] / \
                                xsec.nevents[sample_name]
                        wgts += [x['pu_weight'] * x['lep_scale'] * \
                                scale for x in table.where(cut)]


        plt.figure(figsize=(6, 5))

        (n, xbins, ybins, Image) = plt.hist2d(
                vals1, vals2,
                bins=[nbins1,nbins2],
                range=[[xmin1,xmax1],[xmin2,xmax2]],
                weights=wgts)

        plt.colorbar()
        plt.title(title)
        plt.xlabel(xlab, ha='right', position=(1,0), size='larger')
        plt.ylabel(ylab, ha='right', position=(0,1), size='larger')

        plt.axhspan(450,550,0.375,0.625,fill=False,edgecolor='white')

        plt.tight_layout(0.5)

        self.log.info("Generating Histogram: %s:%s, %s/%s" % (var1,var2, self.out_dir, file_name))

        plt.savefig("%s/%s" % (self.out_dir, file_name))
        plt.clf()
开发者ID:dabelknap,项目名称:DblHAnalysis,代码行数:52,代码来源:plotter.py


示例18: instrumentalness

def instrumentalness():
    global esn, visualiser

    train_skip = sys.argv[1]
    test_skip = sys.argv[2]
    pkl = sys.argv[3] if len(sys.argv) > 3 else None
    n_forget_points = 0

    train_input, train_output, train_splits, test_input, test_output, test_splits, esn = test_data.instrumentalness()

    visualiser = Visualiser(esn, output_yscale=.3)

    if pkl:
        with open(pkl) as f:
            esn.unserialize(cPickle.load(f))
    else:
        esn.train(train_input, train_output, callback=refresh, n_forget_points=n_forget_points, callback_every=int(train_skip), reset_points=train_splits)

    visualiser.set_weights()
    esn.reset_state()

    esn.noise_level = 0

    #test_input, test_output, test_splits = train_input, train_output, train_splits

    import ipdb; ipdb.set_trace()

    print 'test'
    estimated_output = esn.test(test_input, n_forget_points=n_forget_points, callback_every=int(test_skip), callback=refresh, reset_points=test_splits, actual_output=test_output * esn.teacher_scaling + esn.teacher_shift)

    error = nrmse(estimated_output, test_output)
    print 'error: %s' % error

    means = []
    estimated_means = []
    for start, end in zip(test_splits[:-1], test_splits[1:]):
        means.append(np.mean(test_output[start:end]))
        estimated_means.append(np.mean(estimated_output[start:end]))

    plt.plot(means, 'go', markersize=10)
    plt.plot(estimated_means, 'r*', markersize=10)

    for i, (out, est) in enumerate(zip(means, estimated_means)):
        if out > est:
            col = 'c'
        else:
            col = 'y'
            
        i /= float(len(means))
        plt.axhspan(out, est, i - .005, i + 0.005, color=col)

    plt.show()
开发者ID:andreasjansson,项目名称:esn,代码行数:52,代码来源:visualise.py


示例19: vitals_bp

def vitals_bp(request, id):
	"""
	"""
	from ocemr.models import Patient, VitalType, Vital

	p = Patient.objects.get(pk=id)
	vt_bpS= VitalType.objects.get(title="BP - Systolic")
	v_bpS=Vital.objects.filter(patient=p,type=vt_bpS)
	bpS_date_list=[]
	bpS_data_list=[]
	for v in v_bpS:
		bpS_date_list.append(v.observedDateTime)
		bpS_data_list.append(v.data)

	vt_bpD= VitalType.objects.get(title="BP - Diastolic")
	v_bpD=Vital.objects.filter(patient=p,type=vt_bpD)
	bpD_date_list=[]
	bpD_data_list=[]
	for v in v_bpD:
		bpD_date_list.append(v.observedDateTime)
		bpD_data_list.append(v.data)

	import matplotlib
	matplotlib.use('Agg')
	import matplotlib.pyplot as plt

	fig = plt.figure(figsize=(10,5),dpi=75)
	fig.interactive = False
	
	plt.title('Blood Pressure History for %s'%(p))
	plt.grid(True)
	plt.axhspan(ymin=90, ymax=140, color='b',alpha=.2)
	plt.axhspan(ymin=60, ymax=90, color='g',alpha=.2)
	plt.axhline(y=120, color='b')
	plt.axhline(y=80, color='g')
	plt.plot(bpS_date_list, bpS_data_list, 'o-', color='r', label="systolic")
	plt.plot(bpD_date_list, bpD_data_list, 'o-', color='m', label="diastolic")
	plt.ylabel('mmHg')
	plt.legend(loc=0)
	fig.autofmt_xdate()

	fig.text(0.15, 0.33, 'OCEMR',
		fontsize=150, color='gray',
		alpha=0.07)

	plt.draw()
	canvas = matplotlib.backends.backend_agg.FigureCanvasAgg(fig)    
	response = HttpResponse(content_type='image/png')
	canvas.print_png(response)
	plt.close(fig)
	return response
开发者ID:ph1l,项目名称:ocemr,代码行数:51,代码来源:graphs.py


示例20: plotTimeline

def plotTimeline(a, filename):
    # Converts str into a datetime object.
    conv = lambda s: dt.datetime.strptime(s, '%H:%M:%S:%f')

    # Use numpy to read the data in.
    data = np.genfromtxt(a, converters={1: conv, 2: conv}, \
                     names=['caption', 'start', 'stop', 'state'], \
                     dtype=None, delimiter=",")
    cap, start, stop = data['caption'], data['start'], data['stop']

    # Check the status, because we paint all lines with the same color
    # together
    is_ok = (data['state'] == 'OK')
    not_ok = np.logical_not(is_ok)

    # Get unique captions and there indices and the inverse mapping
    captions, unique_idx, caption_inv = np.unique(cap, 1, 1)

    # Build y values from the number of unique captions.
    y = (caption_inv + 1) / float(len(captions) + 1)

    # Plot ok tl black
    timelines(y[is_ok], start[is_ok], stop[is_ok], 'k')
    # Plot fail tl red
    timelines(y[not_ok], start[not_ok], stop[not_ok], 'r')

    # Setup the plot
    ax = plt.gca()
    fig = ax.get_figure()
    fig.set_figheight(6)
    fig.set_figwidth(18)
    ax.xaxis_date()
    myFmt = DateFormatter('%H:%M:%S')
    ax.xaxis.set_major_formatter(myFmt)
    ax.xaxis.set_major_locator(SecondLocator(interval=10)) # used to be SecondLocator(0, interval=20)

    plt.axhspan(0.19, 1, facecolor='0.8', alpha=0.5)

    # To adjust the xlimits a timedelta is needed.
    delta = (stop.max() - start.min())/10

    plt.yticks(y[unique_idx], captions, size=14)
    # plt.ylim(0,1)
    plt.tight_layout()
    plt.gcf().subplots_adjust(bottom=0.1)


    plt.xticks(size = 14)
    plt.xlim(start.min()-delta, stop.max()+delta)
    plt.xlabel('Timeline', size=17)
    plt.savefig(filename, format='eps', dpi=200)
开发者ID:52-41-4d,项目名称:GreyFiber,代码行数:51,代码来源:plotTimeline.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python pyplot.axis函数代码示例发布时间:2022-05-27
下一篇:
Python pyplot.axhline函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap