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


Python pylab.figlegend函数代码示例

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


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

示例1: plot_results

def plot_results(t_hr, I_mA, avg_t_hr, lifetime_hr, lifetime_error = None,
                 show_plot = False):
    """"""
    
    # Set show_plot to True to stop the code here for examining the plot
    if show_plot:
        fig = plt.figure()
            
        ax1 = fig.add_subplot(111)
        h1 = ax1.plot(t_hr, I_mA, '.-', label='Data', linewidth=0.5)
        ax1.set_xlabel('Time [hr]')
        ax1.set_ylabel('Beam Current [mA]')
            
        ax2 = ax1.twinx()
        
        if lifetime_error is not None :
            h2 = ax2.errorbar(avg_t_hr, lifetime_hr,
                              yerr = lifetime_error,
                              fmt = '-', ecolor = 'r',
                              color = 'r', linestyle = '-', marker = '.', 
                              label = 'Lifetime')
        else :
            h2 = ax2.plot(avg_t_hr, lifetime_hr,
                          color = 'r', linestyle = '-', marker = '.',
                          label = 'Lifetime')
            
        ax2.set_ylabel('Lifetime [hr]')
            
        plt.figlegend( (h1[0], h2[0]), 
                       (h1[0].get_label(), h2[0].get_label()), 
                       loc='upper right')

        plt.show()  
开发者ID:ChannelFinder,项目名称:hla,代码行数:33,代码来源:utLifetime.py

示例2: plot

  def plot(self,yl='',yr='',x='s',idx=slice(None),clist='k r b g c m',lattice=True,newfig=True):
    self._clist=clist.split()
    if newfig:
      f=_p.figure()
    else:
      f=_p.gcf()
    sp=_p.subplot(111)
    _p.subplots_adjust(right=0.72)
    _p.setp( sp.yaxis, visible=False)
    xd=getattr(self,x)[idx]
    out=qdplot(figure=f,subplot=sp,plots=[],lines=[],legends=[],xaxis=xd)
    if lattice:
      self._lattice(out,idx,['kn0l','angle'],"#a0ffa0",'Bend h')
      self._lattice(out,idx,['ks0l'],"#ffa0a0",'Bend v')
      self._lattice(out,idx,['kn1l','k1l'],"#a0a0ff",'Quad')
      self._lattice(out,idx,['hkick'],"#e0a0e0",'Kick h')
      self._lattice(out,idx,['vkick'],"#a0e0e0",'Kick v')
    for i in yl.split():
      self._column(out,idx,i,'left')
    for i in yr.split():
      self._column(out,idx,i,'right')

    _p.xlabel(_mylbl(axlabel,x))

    _p.xlim(min(xd),max(xd))
    _p.figlegend(out.lines,out.legends,'upper right')
    _p.grid()
    _p.draw()
    del self._clist
    if hasattr(self,'_colAxleft'): delattr(self,'_colAxleft')
    if hasattr(self,'_colAxright'): delattr(self,'_colAxright')
    self.currplot=out
    return out
开发者ID:BenjaminBerhault,项目名称:Python_Classes4MAD,代码行数:33,代码来源:plotfunc.py

示例3: plot

def plot(x, y, yci, methods, title, xlabel, ylabel, filename):
  fig = pylab.figure()

  ax = pylab.gca()
  for method in methods:
    print method, y(method), yci(method)
    lines = ax.errorbar(x(method), y(method), yci(method), fmt=markers[method], label=legends[method], mfc='none', markersize=15, capsize=5)
  
  # easiest way to plot brute force
  """
  method = 'brute'
  lines = ax.errorbar(range(1,4), [0,] * 3, [0,] * 3, fmt=markers[method], label=legends[method], mfc='none', markersize=15, capsize=5)
  """

  ax.xaxis.set_major_formatter(FormatStrFormatter('%.0f'))

  pylab.title(title)
  pylab.xlabel(xlabel)
  pylab.ylabel(ylabel)
  #pylab.ylim([0, 0.2])
  pylab.gcf().subplots_adjust(bottom=0.2, left=0.2)
  fig.savefig(filename + ".pdf", dpi=300, format="pdf")
  
  figLegend = pylab.figure(figsize = (6, 4))
  pylab.figlegend(*ax.get_legend_handles_labels(), loc = 'upper left')
  figLegend.savefig("legend.pdf", dpi=300, format="pdf")
  
  pylab.close()
开发者ID:shunzh,项目名称:RLCodeBase,代码行数:28,代码来源:plotOfficeNavigation.py

示例4: update

  def update(self):
    if callable(self.pre):
      self.pre()
    _p.ioff()
    self.lines=[]
    self.legends=[]
#    self.figure.lines=[]
#    self.figure.patches=[]
#    self.figure.texts=[]
#    self.figure.images = []
    self.figure.legends = []

    if self.lattice:
      self.lattice.patches=[]
      self._lattice(['k0l','kn0l','angle'],"#a0ffa0",'Bend h')
      self._lattice(['ks0l'],"#ffa0a0",'Bend v')
      self._lattice(['kn1l','k1l'],"#a0a0ff",'Quad')
      self._lattice(['hkick'],"#e0a0e0",'Kick h')
      self._lattice(['vkick'],"#a0e0e0",'Kick v')
    if self.left:
      self.left.lines=[]
      for i in self.yl:
        self._column(i,self.left,self.color[i])
    if self.right:
      self.right.lines=[]
      for i in self.yr:
        self._column(i,self.right,self.color[i])
    _p.xlabel(_mylbl(axlabel,self.x))
    self.figure.gca().set_xlim(min(self.xaxis[self.idx]),max(self.xaxis[self.idx]))
    _p.figlegend(self.lines,self.legends,'upper right')
    _p.grid(True)
#    self.figure.canvas.mpl_connect('button_release_event',self.button_press)
#    self.figure.canvas.mpl_connect('pick_event',self.pick)
    _p.ion()
    _p.draw()
开发者ID:mfittere,项目名称:pyoptics,代码行数:35,代码来源:plotfunc.py

示例5: plotMatches

def plotMatches(imgsources, refsources, matches, wcs, W, H, prefix,
                saveplot=True, format='png'):
    plt.clf()

    # Image sources
    ix = np.array([s.getXAstrom() for s in imgsources])
    iy = np.array([s.getYAstrom() for s in imgsources])
    iflux = np.array([s.getPsfFlux() for s in imgsources])
    I = np.argsort(-iflux)
    # First 200: red dots
    II = I[:200]
    p1 = plt.plot(ix[II], iy[II], 'r.', zorder=10)
    # Rest: tiny dots
    II = I[200:]
    p2 = plt.plot(ix[II], iy[II], 'r.', markersize=1, zorder=9)

    # Ref sources:
    # Only getRa() (not getRaAstrom(), getRaObject()) is non-zero.

    rx,ry = [],[]
    for r in refsources:
        xy = wcs.skyToPixel(r.getRaDec())
        rx.append(xy[0])
        ry.append(xy[1])
    rx = np.array(rx)
    ry = np.array(ry)
    p3 = plt.plot(rx, ry, 'bo', mec='b', mfc='none', markersize=6, zorder=20)

    x,y = [],[]
    dx,dy = [],[]
    for m in matches:
        x0,x1 = m.first.getXAstrom(), m.second.getXAstrom()
        y0,y1 = m.first.getYAstrom(), m.second.getYAstrom()
        #plt.plot([x0, x1], [y0, y1], 'g.-')
        x.append(x0)
        y.append(y0)
        dx.append(x1-x0)
        dy.append(y1-y0)
    #plt.plot(x, y, 's', mec='g', mfc='none', markersize=5)
    p4 = plt.plot(x, y, 'o', mec='g', mfc='g', alpha=0.5, markersize=8, zorder=5)
    p5 = plt.quiver(x, y, dx, dy, angles='xy', scale=30., zorder=30)
    plt.axis('scaled')
    plt.axis([0, W, 0, H])
    #print p1, p2, p3, p4, p5

    plt.figlegend((p1, p2, p3, p4), #, p5),
              ('Image sources (brightest 200)',
               'Image sources (rest)',
               'Reference sources',
               'Matches',),
              'center right',
              numpoints=1,
              prop=FontProperties(size='small'))

    fn = prefix + '-matches.' + format
    return _output(fn, format, saveplot)
开发者ID:jonathansick-shadow,项目名称:meas_astrom,代码行数:56,代码来源:wcsPlots.py

示例6: plot

def plot(cluster, filename="plot.png", func=lambda a: a.id, 
         plot_title='', cmap='Paired', filter=lambda a: True, 
         draw_legend=False, radius='2.25', sym=None):
    ac = rc.load(cluster)
    clusters = rc.load_clusters(cluster)

    p = get_population()
    pops = [0 for i in range(30000)]
    cluster_pops = [] 
    cluster_pop_max = []
    for clust in range(len(clusters)):
        cluster_pops.append(pops[:])
        cluster_pop_max.append([0,0,-1,0])

    for clust,agents in enumerate(clusters):
        for agent in agents:
            a = Agent(agent)
            for i in range(a.birth, a.death):
                cluster_pops[clust][i] += 1
                if cluster_pop_max[clust][2] == -1:
                    cluster_pop_max[clust][2] = i
                if i > cluster_pop_max[clust][3]:
                    cluster_pop_max[clust][3] = i
                if cluster_pops[clust][i] > cluster_pop_max[clust][0]:
                    cluster_pop_max[clust][0] = cluster_pops[clust][i]
                    cluster_pop_max[clust][1] = i
    
    lines=[]
    for i,clust in enumerate(cluster_pops):
        lines.append(pylab.plot(range(30000),clust, 
                         label=("%d: k=%d" % (i, len(clusters[i]))),
                         color=pylab.cm.Paired(float(i)/len(clusters))))

    if draw_legend:
        pylab.figlegend(lines, ["%d: k=%d" % (i, len(clust))
                                    for i,clust in enumerate(clusters)], 
                        'center right', 
                        ncol=((len(clusters)/35)+1), prop=dict(size=6))
    else:
        print "should not draw!!!"

    title = r"Cluster Population ($\epsilon$ = %s, %d clusters)" % (radius, len(clusters))
    pylab.title(title, weight='black')
    pylab.xlabel("Time", weight='bold')
    pylab.ylabel("Population Size", weight='bold')
    if sym is not None:
        pylab.figtext(0,.954, '(%s)' % sym, size=6, weight='black')

    pylab.savefig(filename, dpi=300)

    print 'cluster, totalPop, start, peak, stop, maxPop'
    for clust,agents in enumerate(clusters):
        print clust, len(agents), cluster_pop_max[clust][2], cluster_pop_max[clust][1], cluster_pop_max[clust][3]+1, cluster_pop_max[clust][0]
开发者ID:JaimieMurdock,项目名称:polyworld,代码行数:53,代码来源:agent_cluster_pop.py

示例7: piechart

 def piechart(self, domain_type):
     pie_file = self.output[0]
     pylab.figure(figsize=(5,5))
     
     probs,labels = ([],[])
     for type in DOMAIN_TYPES:
         mean_coverage = mean(domain_type[type]) if len(domain_type[type])>0 else 0.0
         debug(self.family_name,type,mean_coverage)
         probs.append(mean_coverage)
         labels.append(type)#+":%0.2f" % mean_coverage)
     
     #ax = pylab.axes([0.6, 0.6, 0.4, 0.4])
     explode = [0.05 for i in xrange(len(DOMAIN_TYPES))]
     patches, texts = pylab.pie(probs,explode=None,labels=None,shadow=False,colors=DOMAIN_COLORS)
     pylab.figlegend(patches, labels, "lower left", fancybox=True, markerscale=0.2)
     pylab.title(self.family_name)
     pylab.savefig(pie_file)
开发者ID:dpenfoldbrown,项目名称:hpf,代码行数:17,代码来源:map_families.py

示例8: plot_categories

def plot_categories(categories, category_names=None, distribution_names=None, numrows=None, numcols=None):
    "Plot the categories as sub-plots."

    import pylab as P
    assert 2 == len(categories.shape)

    # determine number of rows and columns
    num_dists = categories.shape[0]
    num_categories = categories.shape[1]
    if not numrows and not numcols:
        numrows = int(numpy.sqrt(num_categories))
    if not numrows:
        numrows = num_categories / numcols
        if num_categories % numcols:
            numrows += 1
    elif not numcols:
        numcols = num_categories / numrows
        if num_categories % numrows:
            numcols += 1

    # plot each category
    max, min = categories.max(), categories.min()
    ind = numpy.arange(num_dists)    # the x locations for the groups
    # the width of the bars: can also be len(x) sequence
    width = 1.
    for c in range(num_categories):
        # overlaps, subplot(111) is killed
        splt = P.subplot(numrows, numcols, c + 1)
        handles = [
            P.bar((i,), (x,), width, color=color)
            for color, i, x
            in zip(pylab_utils.simple_colours, ind, categories[:, c])
        ]
        splt.set_ylim(min, max)
        if category_names:
            P.title(category_names[c])
        if c % numcols:
            splt.set_yticklabels(())
        if distribution_names:
            P.xticks(ind + width / 2., distribution_names)
        else:
            splt.set_xticklabels(())
        splt.set_xticks(tuple())
    if distribution_names:
        P.figlegend(handles, distribution_names, 'upper right')
开发者ID:JohnReid,项目名称:infpy,代码行数:45,代码来源:summarise.py

示例9: plot

def plot(cluster_file, filename="plot.png", func=lambda a: a.id, 
         plot_title='', cmap='Paired', filter=lambda a: True, 
         draw_legend=False, radius='2.25', sym=None, run_dir='../run/'):
    """
    Creates a line plot showing population per cluster
    """

    # retrieve cluster data from cluster file
    clusters = rc.load_clusters(cluster_file)

    # grab cluster population
    p = get_population(run_dir=run_dir)

    lines=[]
    for cluster, agents in enumerate(clusters):
        pop_by_time = list(repeat(0, 30000))
        for agent in agents:
            a = Agent(agent)
            for i in range(a.birth, a.death):
                pop_by_time[i] += 1
    
        lines.append(
            pylab.plot(range(30000), pop_by_time, 
                       label=("%d: k=%d" % (i, len(clusters[cluster]))),
                       color=pylab.cm.Paired(float(cluster)/len(clusters))))

    if draw_legend:
        pylab.figlegend(lines, ["%d: k=%d" % (i, len(cluster))
                                    for i,cluster in enumerate(clusters)], 
                        'center right', 
                        ncol=((len(clusters)/35)+1), prop=dict(size=6))

    title = r"Cluster Population ($\epsilon$ = %s, %d clusters)" % (radius, len(clusters))
    pylab.title(title, weight='black')
    pylab.xlabel("Time", weight='bold')
    pylab.ylabel("Population Size", weight='bold')
    if sym is not None:
        pylab.figtext(0,.954, '(%s)' % sym, size=6, weight='black')

    pylab.savefig(filename, dpi=300)
开发者ID:JaimieMurdock,项目名称:polyworld,代码行数:40,代码来源:population.py

示例10: do_plot

def do_plot(data, legend, fn_png):
    pylab.clf()
    pylab.figure(0, (6,8))
    #pylab.axes([left, bottom, width, height])
    # in fractional coordinates
    pylab.axes([0.20, 0.070, 0.76, 0.84])
    handles = []
    labels = []
    for key, symbol, label in legend:
        x = []
        y = []
        for index, lot in enumerate(lots_list):
            av = data.get((key, lot.key))
            if av is not None:
                x.append(av)
                y.append(-index)
        handle = pylab.plot(x, y, symbol)
        handles.append(handle)
        labels.append(label)
    pos = -numpy.arange(len(lots_list))
    ylabels = [lot.key for lot in lots_list]
    pylab.yticks(pos, ylabels, size="small")
    pylab.xticks(size="small")
    #pylab.xlabel(r"Geometric mean of $k_{\theory}/k_{\exp}$", size="small")
    pylab.xlabel(r"$\exp(RMSD(\ln(k_{\theory}) - \ln($k_{\exp})))$", size="small")
    pylab.semilogx()
    pylab.axvline(0.1, color="k", zorder=-5)
    pylab.axvline(1.0, color="k", zorder=-5)
    pylab.axvline(10.0, color="k", zorder=-5)
    for y in 0, -5, -10, -15, -20, -25, -30, -35, -40:
        pylab.axhline(y, color="k", alpha=0.2, lw=10, zorder=-5)
    if len(legend) > 1:
        legend = pylab.figlegend(handles, labels, (0.22,0.915), numpoints=1, handlelength=0, prop={"size":"small"})
        frame = legend.get_frame()
        frame.set_lw(0.0)
    #pylab.xlim(1e-8, 1e5)
    pylab.xlim(1e0, 1e5)
    pylab.ylim(pos[-1]-0.5, 0.5)
    pylab.savefig(fn_png)
开发者ID:n1Ray,项目名称:tamkin,代码行数:39,代码来源:figures.py

示例11:

    pylab.semilogy()
    pylab.fill(
        numpy.concatenate((invtemps, invtemps[::-1])),
        numpy.concatenate((experimental_k*10, experimental_k[::-1]/10)),
        "k", alpha=0.2, lw=0,
    )
    pylab.xticks(
        1/numpy.array([300, 350, 400, 450, 500, 550, 600], float),
        ["300", "350", "400", "450", "500", "550", "600"],
    )
    pylab.title(title)
    pylab.xlabel("T [K]")
    pylab.ylabel("k [(m**3/mol)/s]")
    pylab.ylim(1e-8,1e7)
    legend = pylab.figlegend(
        lines, labels, (0.07,0.06), ncol=3, prop={"size":11},
        handlelength=3, labelspacing=0.1, columnspacing=1
    )
    #legend.get_frame().set_linewidth(0)
    legend.get_frame().set_fill(True)
    legend.get_frame().set_alpha(0.5)
    pylab.savefig(fn_img % "rates")

    pylab.clf()
    lines = []
    labels = []
    line = pylab.plot([experimental_Ea], [experimental_A], color="k", marker="o", ms=11, mew=2, lw=0, ls=" ")
    lines.append(line)
    labels.append("experiment")
    for lot in lots_list:
        if lot.spin == "ROS":
            label = "ro" + lot.label
开发者ID:n1Ray,项目名称:tamkin,代码行数:32,代码来源:kintab.py

示例12: interaction_plot


#.........这里部分代码省略.........
                    yerr = np.array([yerr for a in x])

                plots = []
                labels = []
                for i, name in enumerate(y.rnames):
                    if aggregate != None:
                        yerr = yerrs[i].flatten()
                    
                    labels.append(name[0][1])

                    if all([_isfloat(a) for a in x]):
                        plots.append(
                            axs[-1].errorbar(x, y[i].flatten(), yerr)[0])
                        
                        if xmin == 'AUTO' and xmax == 'AUTO':
                            xmin , xmax = axs[-1].get_xlim()
                            xran = xmax - xmin
                            xmin = xmin - .05*xran
                            xmax = xmax + .05*xran
                            
                        axs[-1].plot([xmin, xmax], [0.,0.], 'k:')
                        
                    else : # categorical x axis
                        plots.append(
                            axs[-1].errorbar(
                                _xrange(len(x)), y[i].flatten(), yerr)[0])
                        
                        pylab.xticks(_xrange(len(x)), x)
                        xmin = - 0.5
                        xmax = len(x) - 0.5
                        
                        axs[-1].plot([xmin, xmax], [0., 0.], 'k:')

                pylab.figlegend(plots, labels, loc=1,
                                labelsep=.005,
                                handlelen=.01,
                                handletextsep=.005)

            test['y'].append(y)
            if yerr == None:
                test['yerr'].append([])
            else:
                test['yerr'].append(yerr)
            test['xmins'].append(xmin)
            test['xmaxs'].append(xmax)

            #  8.2 Add subplot title
            ######################################################
            if rlevels == [1] and clevels == [1]:
                title = ''
                
            elif rlevels == [1]:
                title = _str(clevel)
                
            elif clevels == [1]:
                title = _str(rlevel)
                
            else:
                title = '%s = %s, %s = %s' \
                        % (sepyplots, _str(rlevel),
                           sepxplots, _str(rlevel))
                
            pylab.title(title, fontsize='medium')
            test['subplot_titles'].append(title)

            #  8.3 Format the subplot
开发者ID:marsja,项目名称:pyvttbl,代码行数:67,代码来源:_interaction_plot.py

示例13: main

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('log_dir', nargs='*')
    parser.add_argument('--n_cols', type=int, default=4)
    parser.add_argument('--smoothing', type=float, default=0.6)
    args = parser.parse_args()

    if not args.log_dir:
        raise Exception("Specify at least one log directory")
    for d in args.log_dir:
        if not os.path.exists(d):
            raise Exception(f"Directory {d} does not exist")

    print("Reading events...")
    events_by_log_dir = read_all_events(args.log_dir)

    i = len(os.path.commonprefix(args.log_dir))
    len_longest_suffix = len(os.path.commonprefix([s[::-1] for s in args.log_dir]))
    if len_longest_suffix > 0:
        j = -len_longest_suffix
    else:
        j = None

    print("Plotting...")
    lines, labels = [], []
    plot_n = 1
    axes = {}
    n_graphs = len(set([key for events in events_by_log_dir.values() for key in events.keys()])) + 1
    subplot_dims = (int(ceil(n_graphs / args.n_cols)), args.n_cols)
    figure(figsize=(6 * subplot_dims[1], 4 * subplot_dims[0]))
    for log_dir_n, (log_dir, events) in enumerate(events_by_log_dir.items()):
        print(log_dir)
        color = f"C{log_dir_n % 10}"
        label = log_dir[i:j]
        for key, events in events.items():
            if key not in axes:
                axes[key] = subplot(*(subplot_dims + (plot_n,)))
                plot_n += 1
            ax = axes[key]
            timestamps, values = list(zip(*events))
            relative_timestamps = [t - timestamps[0] for t in timestamps]
            relative_timestamps_hours = [t / 3600 for t in relative_timestamps]
            line = plot_values(ax, values, relative_timestamps_hours, 'Value', 'Time (hours)', key,
                               label=label, color=color, smoothing=args.smoothing)
            lines.append(line)
            labels.append(label)

    unique_lines = []
    unique_labels = []
    for line, label in zip(lines, labels):
        if label not in unique_labels:
            unique_labels.append(label)
            unique_lines.append(line)
    figlegend(unique_lines, unique_labels, loc='upper center')
    tight_layout(rect=[0, 0, 1, 0.90])

    print("Saving figure...")
    # Removing trailing slashes
    normed_log_dirs = [os.path.normpath(d) for d in args.log_dir]
    if len(args.log_dir) == 1:
        out_filename = os.path.basename(normed_log_dirs[0])
    else:
        longest_common_prefix = os.path.commonprefix(normed_log_dirs)
        longest_common_suffix = os.path.commonprefix([d[::-1] for d in normed_log_dirs])[::-1]
        out_filename = longest_common_prefix + '*' + longest_common_suffix + '.png'
    savefig(out_filename)
开发者ID:mrahtz,项目名称:dotfiles,代码行数:66,代码来源:plot_tb.py

示例14: x

        P.close()

    # do AUC bar-chart
    #P.rcParams['xtick.direction'] = 'out'
    def x(a, b, m):
        return b*(len(methods)+1) + m
    P.figure(figsize=(14,6))
    for a, auc in enumerate(('AUC', 'AUC50')):
        ax = P.subplot(1, 2, a+1)
        xlocs = []
        xlabels = []
        for b, bg in enumerate(harness.options.backgrounds):
            rects = P.bar(
                [x(a, b, m) for m in xrange(len(methods))],
                [aucs[bg][auc][method] for method in methods],
                color=[colors[method] for method in methods],
                width=1.
            )
            xlocs.append(x(a, b, len(methods)/2.))
            xlabels.append(bg)
        P.xticks(xlocs, xlabels)
        P.ylim(0,1)
        P.title(auc)
        for tl in ax.get_xticklines():
            tl.set_visible(False)
    #P.text(.5, .9, '%s' % fragment, horizontalalignment='center')
    P.figlegend(rects, methods, loc='upper right')
    P.savefig(os.path.join(options.results_dir, 'AUC-%s.png' % fragment))
    P.savefig(os.path.join(options.results_dir, 'AUC-%s.eps' % fragment))
    P.close()
开发者ID:JohnReid,项目名称:biopsy,代码行数:30,代码来源:test_generate_rocs.py

示例15: plot_icd_vs_mass


#.........这里部分代码省略.........


    # Add the box and whiskers
    galaxies2 = filter(lambda galaxy: galaxy.ston_J > 30., galaxies)
    galaxies2 = pyl.asarray(galaxies2)
    x = [galaxy.Mass for galaxy in galaxies2]
    ll = 8.5
    ul= 12
    #bins_x =pyl.linspace(ll, ul, 7)
    #bins_x =pyl.arange(8.5, 12.5, 0.5)
    bins_x =pyl.array([8.5, 9., 9.5, 10., 10.5, 11., 12.])
    grid = []

    for i in range(bins_x.size-1):
        xmin = bins_x[i]
        xmax = bins_x[i+1]
        cond=[cond1 and cond2 for cond1, cond2 in zip(x>=xmin, x<xmax)]

        grid.append(galaxies2.compress(cond))
    icd = []
    for i in range(len(grid)):
        icd.append([galaxy.ICD_JH*100 for galaxy in grid[i]])
    #bp2 = f1s2.boxplot(icd, positions=pyl.delete(bins_x,-1)+0.25, sym='')
    pbp(f1s3, icd, indexer=list(pyl.delete(bins_x,-1)+0.25))
    pbp(f1s4, icd, indexer=list(pyl.delete(bins_x,-1)+0.25))

    # Finish Plot
    # Tweak colors on the boxplot
    #pyl.setp(bp1['boxes'], lw=2)
    #pyl.setp(bp1['whiskers'], lw=2)
    #pyl.setp(bp1['medians'], lw=2)
    #pyl.setp(bp2['boxes'], lw=2)
    #pyl.setp(bp2['whiskers'], lw=2)
    #pyl.setp(bp2['medians'], lw=2)
    #pyl.setp(bp['fliers'], color='#8CFF6F', marker='+')

    #f1s1.axvspan(7.477, 9, facecolor='#FFFDD0', ec='None', zorder=0)
    #f1s1.axvspan(11, 12, facecolor='#FFFDD0', ec='None', zorder=0)
    #f1s2.axvspan(7.477, 9, facecolor='#FFFDD0', ec='None', zorder=0)
    #f1s2.axvspan(11, 12, facecolor='#FFFDD0', ec='None', zorder=0)

    f1s1.set_xlim(8,12)
    f1s2.set_xlim(8,12)
    f1s3.set_xlim(8,12)
    f1s4.set_xlim(8,12)

    f1s1.set_ylim(-10,50)
    f1s2.set_ylim(0,15)
    f1s3.set_ylim(-5,12)
    f1s4.set_ylim(-1,3)

    f1s1.set_xticks([8,9,10,11,12])
    f1s1.set_xticklabels([])
    f1s2.set_xticks([8,9,10,11,12])
    f1s2.set_xticklabels([])
    f1s3.set_xticks([8,9,10,11,12])
    f1s4.set_xticks([8,9,10,11,12])

    f1s4.set_yticks([-1, 0, 1, 2, 3])

    f1s3.set_xlabel(r"Log Mass ($M_{\odot})$")
    f1s1.set_ylabel(r"$\xi[i_{775},H_{160}]$ (%)")
    f1s4.set_xlabel(r"Log Mass ($M_{\odot})$")
    f1s3.set_ylabel(r"$\xi[J_{125},H_{160}]$ (%)")

    import matplotlib.font_manager
    line1 = pyl.Line2D([], [], marker='o', mfc='0.8', mec='0.8', markersize=8,
        linewidth=0)
    line2 = pyl.Line2D([], [], marker='s', mec='blue', mfc='None',
        markersize=10, linewidth=0, markeredgewidth=2)
    line3 = pyl.Line2D([], [], color='r', linewidth=2)
    prop = matplotlib.font_manager.FontProperties(size='small')
    pyl.figlegend((line1, line2, line3), ('Data', 'Quartiles',
        'Medians'), 'lower center', prop=prop, ncol=3)

    from matplotlib.patches import ConnectionPatch
    xy = (12, 15)
    xy2 = (8, 15)
    con = ConnectionPatch(xyA=xy, xyB=xy2, coordsA='data', coordsB='data',
        axesA=f1s1, axesB=f1s2)
    xy = (12, 0)
    xy2 = (8, 0)
    con2 = ConnectionPatch(xyA=xy, xyB=xy2, coordsA='data', coordsB='data',
        axesA=f1s1, axesB=f1s2)
    f1s1.add_artist(con)
    f1s1.add_artist(con2)

    xy = (12, 3)
    xy2 = (8, 3)
    con = ConnectionPatch(xyA=xy, xyB=xy2, coordsA='data', coordsB='data',
        axesA=f1s3, axesB=f1s4)
    xy = (12, -1)
    xy2 = (8, -1)
    con2 = ConnectionPatch(xyA=xy, xyB=xy2, coordsA='data', coordsB='data',
        axesA=f1s3, axesB=f1s4)
    f1s3.add_artist(con)
    f1s3.add_artist(con2)

    pyl.draw()
    pyl.show()
开发者ID:boada,项目名称:ICD,代码行数:101,代码来源:plot_icd_mass_box.py


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