Python pylab 模块,colorbar() 实例源码

我们从Python开源项目中,提取了以下40个代码示例,用于说明如何使用pylab.colorbar()

项目:tap    作者:mfouesneau    | 项目源码 | 文件源码
def plot_density_map(x, y, xbins, ybins, Nlevels=4, cbar=True, weights=None):

    Z = np.histogram2d(x, y, bins=(xbins, ybins), weights=weights)[0].astype(float).T

    # central values
    lt = get_centers_from_bins(xbins)
    lm = get_centers_from_bins(ybins)
    cX, cY = np.meshgrid(lt, lm)
    X, Y = np.meshgrid(xbins, ybins)

    im = plt.pcolor(X, Y, Z, cmap=plt.cm.Blues)
    plt.contour(cX, cY, Z, levels=nice_levels(Z, Nlevels), cmap=plt.cm.Greys_r)

    if cbar:
        cb = plt.colorbar(im)
    else:
        cb = None
    plt.xlim(xbins[0], xbins[-1])
    plt.ylim(ybins[0], ybins[-1])

    try:
        plt.tight_layout()
    except Exception as e:
        print(e)
    return plt.gca(), cb
项目:ugali    作者:DarkEnergySurvey    | 项目源码 | 文件源码
def twoDimensionalScatter(title, title_x, title_y,
                          x, y,
                          lim_x = None, lim_y = None,
                          color = 'b', size = 20, alpha=None):
    """
    Create a two-dimensional scatter plot.

    INPUTS
    """
    pylab.figure()

    pylab.scatter(x, y, c=color, s=size, alpha=alpha, edgecolors='none')

    pylab.xlabel(title_x)
    pylab.ylabel(title_y)
    pylab.title(title)
    if type(color) is not str:
        pylab.colorbar()

    if lim_x:
        pylab.xlim(lim_x[0], lim_x[1])
    if lim_y:
        pylab.ylim(lim_y[0], lim_y[1])

############################################################
项目:AdK_analysis    作者:orbeckst    | 项目源码 | 文件源码
def plot(self,**kwargs):
        """plot landscape (kwargs are passed on to imshow()

        Use interpolation='bilinear' or 'bicubic' for a smooth
        surface. Default is 'nearest', which shows exact bin
        boundaries.
        """
        import pylab

        kwargs.setdefault('interpolation','nearest')
        pylab.clf()
        pylab.xlabel('x')
        pylab.ylabel('y')
        pylab.imshow(self.pmf_masked.T,**kwargs)
        pylab.colorbar()
        pylab.show()
项目:pyrsss    作者:butala    | 项目源码 | 文件源码
def add_colorbar(ax, im, side='right', size='5%', pad=0.1, **kwds):
    """
    Add colorbar to the axes *ax* with colors corresponding to the
    color mappable object *im*. Place the colorbar at the *side* of
    *ax* (options are `'right'`, `'left'`, `'top'`, or
    `'bottom'`). The width (or height) of the colorbar is specified by
    *size* and is relative to *ax*. Add space *pad* between *ax* and
    the colorbar. The remaining keyword arguments *kwds* are passed to
    the call to :func:`colorbar`. Return the colorbar instance.

    Reference: http://matplotlib.org/mpl_toolkits/axes_grid/users/overview.html
    """
    divider = make_axes_locatable(ax)
    cax = divider.append_axes(side, size=size, pad=pad)
    cb = PL.colorbar(im, cax=cax, **kwds)
    PL.axes(ax)
    return cb
项目:ugali    作者:DarkEnergySurvey    | 项目源码 | 文件源码
def drawStellarDensity(self,ax=None):
        if not ax: ax = plt.gca()
        # Stellar Catalog
        self._create_catalog()
        catalog = self.catalog
        #catalog=ugali.observation.catalog.Catalog(self.config,roi=self.roi)
        pix = ang2pix(self.nside, catalog.lon, catalog.lat)
        counts = collections.Counter(pix)
        pixels, number = numpy.array(sorted(counts.items())).T
        star_map = healpy.UNSEEN * numpy.ones(healpy.nside2npix(self.nside))
        star_map[pixels] = number
        star_map = numpy.where(star_map == 0, healpy.UNSEEN, star_map)

        #im = healpy.gnomview(star_map,**self.gnom_kwargs)
        #healpy.graticule(dpar=1,dmer=1,color='0.5',verbose=False)
        #pylab.close()

        im = drawHealpixMap(star_map,self.glon,self.glat,self.radius,coord=self.coord)
        #im = ax.imshow(im,origin='bottom')
        try:    ax.cax.colorbar(im)
        except: pylab.colorbar(im,ax=ax)
        ax.annotate("Stars",**self.label_kwargs)
        return im
项目:PyPeVoc    作者:goiosunsw    | 项目源码 | 文件源码
def plot_time_freq(self, colors=True, ax=None):
        import pylab as pl

        if ax is None:
            fig, allax = pl.subplots(1)
            ax = allax

        # make time matrix same shape as others
        t = np.outer(self.t, np.ones(self.npeaks))
        f = self.f
        if colors:
            mag = 20*np.log10(self.mag)
            ax.scatter(t, f, s=6, c=mag, lw=0)
        else:
            mag = 100 + 20*np.log10(self.mag)
            ax.scatter(t, f, s=mag, lw=0)
        pl.xlabel('Time (s)')
        pl.ylabel('Frequency (Hz)')
        # if colors:
        # cs = pl.colorbar(ax=ax)
        # cs.set_label('Magnitude (dB)')
        # pl.show()
        return ax
项目:PyPeVoc    作者:goiosunsw    | 项目源码 | 文件源码
def plot_time_mag(self):
        import pylab as pl

        pl.figure()
        t = np.outer(self.t, np.ones(self.npeaks))
        # f = np.log2(self.f)
        f = self.f
        mag = 20*np.log10(self.mag)
        pl.scatter(t, mag, s=10, c=f, lw=0,
                   norm=pl.matplotlib.colors.LogNorm())
        pl.xlabel('Time (s)')
        pl.ylabel('Magnitude (dB)')
        cs = pl.colorbar()
        cs.set_label('Frequency (Hz)')
        # pl.show()
        return pl.gca()
项目:hco-experiments    作者:zooniverse    | 项目源码 | 文件源码
def visualiseNormObject(self):
        shape = (2*self.extent, 2*self.extent)
        pylab.ion()
        pylab.clf()
        #pylab.set_cmap("bone")
        pylab.hot()
        pylab.title("image: %s" % self.fitsFile)
        pylab.imshow(np.reshape(self.signPreserveNorm(), shape, order="F"), interpolation="nearest")
        pylab.plot(np.arange(0,2*self.extent), self.extent*np.ones((2*self.extent,)), "r--")
        pylab.plot(self.extent*np.ones((2*self.extent,)), np.arange(0,2*self.extent), "r--")
        pylab.colorbar()
        pylab.ylim(-1, 2*self.extent)
        pylab.xlim(-1, 2*self.extent)
        pylab.xlabel("Pixels")
        pylab.ylabel("Pixels")
        pylab.show()
项目:hco-experiments    作者:zooniverse    | 项目源码 | 文件源码
def visualiseNormObject(self):
        shape = (2*self.extent, 2*self.extent)
        pylab.ion()
        pylab.clf()
        #pylab.set_cmap("bone")
        pylab.hot()
        pylab.title("image: %s" % self.fitsFile)
        pylab.imshow(np.reshape(self.signPreserveNorm(), shape, order="F"), interpolation="nearest")
        pylab.plot(np.arange(0,2*self.extent), self.extent*np.ones((2*self.extent,)), "r--")
        pylab.plot(self.extent*np.ones((2*self.extent,)), np.arange(0,2*self.extent), "r--")
        pylab.colorbar()
        pylab.ylim(-1, 2*self.extent)
        pylab.xlim(-1, 2*self.extent)
        pylab.xlabel("Pixels")
        pylab.ylabel("Pixels")
        pylab.show()
项目:livespin    作者:biocompibens    | 项目源码 | 文件源码
def plotAgainstGFP_hist2d(self):
        fig1 = pylab.figure(figsize = (20, 15))
        print len(self.GFP)
        for i in xrange(min(len(data.cat), 4)):
            print len(self.GFP[self.categories == i])
            vect = []
            pylab.subplot(2,2,i+1)
            pop = self.GFP[self.categories == i]
            print "cat", i, "n pop", len(self.GFP[(self.categories == i) & (self.GFP > -np.log(12.5))])
            H, xedges, yedges = np.histogram2d(self.angles[self.categories == i], self.GFP[self.categories == i], bins = 10)
            hist = pylab.hist2d(self.GFP[self.categories == i], self.angles[self.categories == i], bins = 10, cmap = pylab.cm.Reds, normed = True)
            pylab.clim(0.,0.035)
            pylab.colorbar()
            pylab.title(data.cat[i])
            pylab.xlabel('GFP score')
            pylab.ylabel('Angle (degree)')
            pylab.xlim([-4.2, -1])
        pylab.show()
项目:IntroToDeepLearning    作者:robb-brown    | 项目源码 | 文件源码
def plotFields(layer,fieldShape=None,channel=None,figOffset=1,cmap=None,padding=0.01):
    # Receptive Fields Summary
    try:
        W = layer.W
    except:
        W = layer
    wp = W.eval().transpose();
    if len(np.shape(wp)) < 4:       # Fully connected layer, has no shape
        fields = np.reshape(wp,list(wp.shape[0:-1])+fieldShape) 
    else:           # Convolutional layer already has shape
        features, channels, iy, ix = np.shape(wp)
        if channel is not None:
            fields = wp[:,channel,:,:]
        else:
            fields = np.reshape(wp,[features*channels,iy,ix])

    perRow = int(math.floor(math.sqrt(fields.shape[0])))
    perColumn = int(math.ceil(fields.shape[0]/float(perRow)))

    fig = mpl.figure(figOffset); mpl.clf()

    # Using image grid
    from mpl_toolkits.axes_grid1 import ImageGrid
    grid = ImageGrid(fig,111,nrows_ncols=(perRow,perColumn),axes_pad=padding,cbar_mode='single')
    for i in range(0,np.shape(fields)[0]):
        im = grid[i].imshow(fields[i],cmap=cmap); 

    grid.cbar_axes[0].colorbar(im)
    mpl.title('%s Receptive Fields' % layer.name)

    # old way
    # fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))])
    # tiled = []
    # for i in range(0,perColumn*perRow,perColumn):
    #   tiled.append(np.hstack(fields2[i:i+perColumn]))
    # 
    # tiled = np.vstack(tiled)
    # mpl.figure(figOffset); mpl.clf(); mpl.imshow(tiled,cmap=cmap); mpl.title('%s Receptive Fields' % layer.name); mpl.colorbar();
    mpl.figure(figOffset+1); mpl.clf(); mpl.imshow(np.sum(np.abs(fields),0),cmap=cmap); mpl.title('%s Total Absolute Input Dependency' % layer.name); mpl.colorbar()
项目:IntroToDeepLearning    作者:robb-brown    | 项目源码 | 文件源码
def plotOutput(layer,feed_dict,fieldShape=None,channel=None,figOffset=1,cmap=None):
    # Output summary
    try:
        W = layer.output
    except:
        W = layer
    wp = W.eval(feed_dict=feed_dict);
    if len(np.shape(wp)) < 4:       # Fully connected layer, has no shape
        temp = np.zeros(np.product(fieldShape)); temp[0:np.shape(wp.ravel())[0]] = wp.ravel()
        fields = np.reshape(temp,[1]+fieldShape)
    else:           # Convolutional layer already has shape
        wp = np.rollaxis(wp,3,0)
        features, channels, iy,ix = np.shape(wp)
        if channel is not None:
            fields = wp[:,channel,:,:]
        else:
            fields = np.reshape(wp,[features*channels,iy,ix])

    perRow = int(math.floor(math.sqrt(fields.shape[0])))
    perColumn = int(math.ceil(fields.shape[0]/float(perRow)))
    fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))])
    tiled = []
    for i in range(0,perColumn*perRow,perColumn):
        tiled.append(np.hstack(fields2[i:i+perColumn]))

    tiled = np.vstack(tiled)
    if figOffset is not None:
        mpl.figure(figOffset); mpl.clf(); 

    mpl.imshow(tiled,cmap=cmap); mpl.title('%s Output' % layer.name); mpl.colorbar();
项目:IntroToDeepLearning    作者:robb-brown    | 项目源码 | 文件源码
def plotFields(layer,fieldShape=None,channel=None,maxFields=25,figName='ReceptiveFields',cmap=None,padding=0.01):
    # Receptive Fields Summary
    W = layer.W
    wp = W.eval().transpose();
    if len(np.shape(wp)) < 4:       # Fully connected layer, has no shape
        fields = np.reshape(wp,list(wp.shape[0:-1])+fieldShape)
    else:           # Convolutional layer already has shape
        features, channels, iy, ix = np.shape(wp)
        if channel is not None:
            fields = wp[:,channel,:,:]
        else:
            fields = np.reshape(wp,[features*channels,iy,ix])

    fieldsN = min(fields.shape[0],maxFields)
    perRow = int(math.floor(math.sqrt(fieldsN)))
    perColumn = int(math.ceil(fieldsN/float(perRow)))

    fig = mpl.figure(figName); mpl.clf()

    # Using image grid
    from mpl_toolkits.axes_grid1 import ImageGrid
    grid = ImageGrid(fig,111,nrows_ncols=(perRow,perColumn),axes_pad=padding,cbar_mode='single')
    for i in range(0,fieldsN):
        im = grid[i].imshow(fields[i],cmap=cmap);

    grid.cbar_axes[0].colorbar(im)
    mpl.title('%s Receptive Fields' % layer.name)

    # old way
    # fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))])
    # tiled = []
    # for i in range(0,perColumn*perRow,perColumn):
    #   tiled.append(np.hstack(fields2[i:i+perColumn]))
    #
    # tiled = np.vstack(tiled)
    # mpl.figure(figOffset); mpl.clf(); mpl.imshow(tiled,cmap=cmap); mpl.title('%s Receptive Fields' % layer.name); mpl.colorbar();
    mpl.figure(figName+' Total'); mpl.clf(); mpl.imshow(np.sum(np.abs(fields),0),cmap=cmap); mpl.title('%s Total Absolute Input Dependency' % layer.name); mpl.colorbar()
项目:IntroToDeepLearning    作者:robb-brown    | 项目源码 | 文件源码
def plotOutput(layer,feed_dict,fieldShape=None,channel=None,figOffset=1,cmap=None):
    # Output summary
    W = layer.output
    wp = W.eval(feed_dict=feed_dict);
    if len(np.shape(wp)) < 4:       # Fully connected layer, has no shape
        temp = np.zeros(np.product(fieldShape)); temp[0:np.shape(wp.ravel())[0]] = wp.ravel()
        fields = np.reshape(temp,[1]+fieldShape)
    else:           # Convolutional layer already has shape
        wp = np.rollaxis(wp,3,0)
        features, channels, iy,ix = np.shape(wp)
        if channel is not None:
            fields = wp[:,channel,:,:]
        else:
            fields = np.reshape(wp,[features*channels,iy,ix])

    perRow = int(math.floor(math.sqrt(fields.shape[0])))
    perColumn = int(math.ceil(fields.shape[0]/float(perRow)))
    fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))])
    tiled = []
    for i in range(0,perColumn*perRow,perColumn):
        tiled.append(np.hstack(fields2[i:i+perColumn]))

    tiled = np.vstack(tiled)
    if figOffset is not None:
        mpl.figure(figOffset); mpl.clf();

    mpl.imshow(tiled,cmap=cmap); mpl.title('%s Output' % layer.name); mpl.colorbar();
项目:spyking-circus    作者:spyking-circus    | 项目源码 | 文件源码
def view_whitening(data):
    pylab.subplot(121)
    pylab.imshow(data['spatial'], interpolation='nearest')
    pylab.title('Spatial')
    pylab.xlabel('# Electrode')
    pylab.ylabel('# Electrode')
    pylab.colorbar()
    pylab.subplot(122)
    pylab.title('Temporal')
    pylab.plot(data['temporal'])
    pylab.xlabel('Time [ms]')
    x, y = pylab.xticks()
    pylab.xticks(x, (x-x[-1]//2)//10)
    pylab.tight_layout()
项目:spyking-circus    作者:spyking-circus    | 项目源码 | 文件源码
def get_performance(file_name, name):

    a, b            = os.path.splitext(os.path.basename(file_name))
    file_name, ext  = os.path.splitext(file_name)
    file_out        = os.path.join(os.path.abspath(file_name), a)
    data            = {}
    result          = h5py.File(file_out + '.basis.hdf5')
    data['spatial']  = result.get('spatial')[:]
    data['temporal'] = numpy.zeros(61) #result.get('temporal')[:]

    pylab.figure()
    pylab.subplot(121)
    pylab.imshow(data['spatial'], interpolation='nearest')
    pylab.title('Spatial')
    pylab.xlabel('# Electrode')
    pylab.ylabel('# Electrode')
    pylab.colorbar()
    pylab.subplot(122)
    pylab.title('Temporal')
    pylab.plot(data['temporal'])
    pylab.xlabel('Time [ms]')
    x, y = pylab.xticks()
    pylab.xticks(x, (x-x[-1]//2)//10)
    pylab.tight_layout()
    plot_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '.'))
    plot_path = os.path.join(plot_path, 'plots')
    plot_path = os.path.join(plot_path, 'whitening')
    if not os.path.exists(plot_path):
        os.makedirs(plot_path)
    output = os.path.join(plot_path, '%s.pdf' %name)
    pylab.savefig(output)

    return data
项目:emc_and_dm    作者:eucall-software    | 项目源码 | 文件源码
def make_panel_of_intensity_slices(fn, c_n=9):
    M.rcParams.update({'font.size': 13})
    intensList = read.extract_arr_from_h5(fn, "/history/intensities", n=c_n)
    quatList = read.extract_arr_from_h5(fn, "/history/quaternion", n=-1)
    P.ioff()
    intens_len  = len(intensList)
    sqrt_len    = int(N.sqrt(intens_len))
    intens_sh   = intensList[0].shape
    iter_labels = read.create_interval_labels(len(quatList), c_n)[:intens_len]
    to_plot     = intensList[:intens_len]
    quat_label  = quatList[N.array(iter_labels)-1][:intens_len]
    plot_titles = ["iter_%d, quat_%d"%(ii,jj) for ii,jj in zip(iter_labels, quat_label)]
    fig, ax     = P.subplots(sqrt_len, sqrt_len, sharex=True, sharey=True, figsize=(1.8*sqrt_len, 2.*sqrt_len))
    plt_counter = 0
    for r in range(sqrt_len):
        for c in range(sqrt_len):
            ax[r,c].set_title(plot_titles[plt_counter])
            curr_slice = to_plot[plt_counter][intens_sh[0]/2]
            curr_slice = curr_slice*(curr_slice>0.) + 1.E-8*(curr_slice<=0.)
            ax[r,c].set_title(plot_titles[plt_counter], fontsize=11.5)
            im = ax[r,c].imshow(N.log10(curr_slice), vmin=-6.5, vmax=-3.5, aspect='auto', cmap=P.cm.coolwarm)
            plt_counter += 1
    fig.subplots_adjust(wspace=0.01)
    (shx, shy) = curr_slice.shape
    (h_shx, h_shy) = (shx/2, shy/2)
    xt = N.linspace(0.5*h_shx, shx-.5*h_shx-1, 3).astype('int')
    xt_l = N.linspace(-0.5*h_shx, 0.5*h_shx, 3).astype('int')
    yt = N.linspace(0, shy-1, 3).astype('int')
    yt_l = N.linspace(-1*h_shy, h_shy, 3).astype('int')
    P.setp(ax, xticks=xt, xticklabels=xt_l, yticks=yt, yticklabels=yt_l)
    cbar_ax = fig.add_axes([0.9, 0.1, 0.025, 0.8])
    fig.colorbar(im, cax=cbar_ax, label="log10(intensities)")
    img_name = "recon_series.pdf"
    P.savefig(img_name, bbox_inches='tight')
    print("Image has been saved as %s" % img_name)
    P.close(fig)
项目:ugali    作者:DarkEnergySurvey    | 项目源码 | 文件源码
def twoDimensionalHistogram(title, title_x, title_y,
                            z, bins_x, bins_y,
                            lim_x=None, lim_y=None,
                            vmin=None, vmax=None):
    """
    Create a two-dimension histogram plot or binned map.

    If using the outputs of numpy.histogram2d, remember to transpose the histogram.

    INPUTS
    """
    pylab.figure()

    mesh_x, mesh_y = numpy.meshgrid(bins_x, bins_y)

    if vmin != None and vmin == vmax:
        pylab.pcolor(mesh_x, mesh_y, z)
    else:
        pylab.pcolor(mesh_x, mesh_y, z, vmin=vmin, vmax=vmax)
    pylab.xlabel(title_x)
    pylab.ylabel(title_y)
    pylab.title(title)
    pylab.colorbar()

    if lim_x:
        pylab.xlim(lim_x[0], lim_x[1])
    if lim_y:
        pylab.ylim(lim_y[0], lim_y[1])

############################################################
项目:ugali    作者:DarkEnergySurvey    | 项目源码 | 文件源码
def drawTS(self,ax=None, filename=None, zidx=0):
        if not ax: ax = plt.gca()
        if not filename:
            #dirname = self.config.params['output2']['searchdir']
            #basename = self.config.params['output2']['mergefile']
            #filename = os.path.join(dirname,basename)
            filename = self.config.mergefile

        results=pyfits.open(filename)[1]
        pixels = results.data['PIXEL']
        values = 2*results.data['LOG_LIKELIHOOD']
        if values.ndim == 1: values = values.reshape(-1,1)
        ts_map = healpy.UNSEEN * numpy.ones(healpy.nside2npix(self.nside))
        # Sum through all distance_moduli
        #ts_map[pixels] = values.sum(axis=1)
        # Just at maximum slice from object

        ts_map[pixels] = values[:,zidx]

        #im = healpy.gnomview(ts_map,**self.gnom_kwargs)
        #healpy.graticule(dpar=1,dmer=1,color='0.5',verbose=False)
        #pylab.close()
        #im = ax.imshow(im,origin='bottom')

        im = drawHealpixMap(ts_map,self.glon,self.glat,self.radius,coord=self.coord)

        try: ax.cax.colorbar(im)
        except: pylab.colorbar(im)
        ax.annotate("TS",**self.label_kwargs)
        return im
项目:ugali    作者:DarkEnergySurvey    | 项目源码 | 文件源码
def drawCMD(self, ax=None, radius=None, zidx=None):
        if not ax: ax = plt.gca()
        import ugali.isochrone

        if zidx is not None:
            filename = self.config.mergefile
            logger.debug("Opening %s..."%filename)
            f = pyfits.open(filename)
            distance_modulus = f[2].data['DISTANCE_MODULUS'][zidx]

            iso = ugali.isochrone.Padova(age=12,z=0.0002,mod=distance_modulus)
            #drawIsochrone(iso,ls='',marker='.',ms=1,c='k')
            drawIsochrone(iso)

        # Stellar Catalog
        self._create_catalog()
        if radius is not None:
            sep = ugali.utils.projector.angsep(self.glon,self.glat,self.catalog.lon,self.catalog.lat)
            cut = (sep < radius)
            catalog_cmd = self.catalog.applyCut(cut)
        else:
            catalog_cmd = self.catalog

        ax.scatter(catalog_cmd.color, catalog_cmd.mag,color='b',marker='.',s=1)
        ax.set_xlim(self.roi.bins_color[0],self.roi.bins_color[-1])
        ax.set_ylim(self.roi.bins_mag[-1],self.roi.bins_mag[0])
        ax.set_xlabel('Color (mag)')
        ax.set_ylabel('Magnitude (mag)')

        try:    ax.cax.colorbar(im)
        except: pass
        ax.annotate("Stars",**self.label_kwargs)
项目:ugali    作者:DarkEnergySurvey    | 项目源码 | 文件源码
def drawMembersSpatial(self,data):
        ax = plt.gca()
        if isinstance(data,basestring):
            filename = data
            data = pyfits.open(filename)[1].data

        xmin, xmax = -0.25,0.25
        ymin, ymax = -0.25,0.25
        xx,yy = np.meshgrid(np.linspace(xmin,xmax),np.linspace(ymin,ymax))

        x_prob, y_prob = sphere2image(self.ra, self.dec, data['RA'], data['DEC'])

        sel = (x_prob > xmin)&(x_prob < xmax) & (y_prob > ymin)&(y_prob < ymax)
        sel_prob = data['PROB'][sel] > 5.e-2
        index_sort = numpy.argsort(data['PROB'][sel][sel_prob])

        plt.scatter(x_prob[sel][~sel_prob], y_prob[sel][~sel_prob], 
                      marker='o', s=2, c='0.75', edgecolor='none')
        sc = plt.scatter(x_prob[sel][sel_prob][index_sort], 
                         y_prob[sel][sel_prob][index_sort], 
                         c=data['PROB'][sel][sel_prob][index_sort], 
                         marker='o', s=10, edgecolor='none', cmap='jet', vmin=0., vmax=1.) # Spectral_r

        drawProjImage(xx,yy,None,coord='C')

        #ax.set_xlim(xmax, xmin)
        #ax.set_ylim(ymin, ymax)
        #plt.xlabel(r'$\Delta \alpha_{2000}\,(\deg)$')
        #plt.ylabel(r'$\Delta \delta_{2000}\,(\deg)$')
        plt.xticks([-0.2, 0., 0.2])
        plt.yticks([-0.2, 0., 0.2])

        divider = make_axes_locatable(ax)
        ax_cb = divider.new_horizontal(size="7%", pad=0.1)
        plt.gcf().add_axes(ax_cb)
        pylab.colorbar(sc, cax=ax_cb, orientation='vertical', ticks=[0, 0.2, 0.4, 0.6, 0.8, 1.0], label='Membership Probability')
        ax_cb.yaxis.tick_right()
项目:hco-experiments    作者:zooniverse    | 项目源码 | 文件源码
def visualiseObject(self, cmap="hot"):
        pylab.ion()
        #pylab.set_cmap("gray")
        pylab.gray()
        pylab.title("image: %s" % self.fitsFile)
        pylab.imshow(self.getObject(), interpolation="nearest", cmap=cmap)
        pylab.colorbar()
        pylab.ylim(-1, 2*self.extent)
        pylab.xlim(-1, 2*self.extent)
        pylab.xlabel("Pixels")
        pylab.ylabel("Pixels")
        pylab.show()
项目:hco-experiments    作者:zooniverse    | 项目源码 | 文件源码
def visualiseObject(self, cmap="hot"):
        pylab.ion()
        #pylab.set_cmap("gray")
        pylab.gray()
        pylab.title("image: %s" % self.fitsFile)
        pylab.imshow(self.getObject(), interpolation="nearest", cmap=cmap)
        pylab.colorbar()
        pylab.ylim(-1, 2*self.extent)
        pylab.xlim(-1, 2*self.extent)
        pylab.xlabel("Pixels")
        pylab.ylabel("Pixels")
        pylab.show()
项目:dlcv05    作者:telecombcn-dl    | 项目源码 | 文件源码
def nice_imshow(ax, data, vmin=None, vmax=None, cmap=None):
    """Wrapper around pl.imshow"""
    if cmap is None:
        cmap = cm.jet
    if vmin is None:
        vmin = data.min()
    if vmax is None:
        vmax = data.max()
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="5%", pad=0.05)
    im = ax.imshow(data, vmin=vmin, vmax=vmax, interpolation='nearest', cmap=cmap)
    pl.colorbar(im, cax=cax)
项目:actinf    作者:x75    | 项目源码 | 文件源码
def plot_hebbsom_links_distances_activations(X, Y, mdl, predictions, distances, activities):
    """plot the hebbian link matrix, and all node distances and activities for all inputs"""


    hebblink_log = np.log(mdl.hebblink_filter.T + 1.0)

    fig4 = pl.figure()
    fig4.suptitle("Debugging SOM: hebbian links, distances, activities (%s)" % (mdl.__class__.__name__))
    gs = gridspec.GridSpec(4, 1)
    # pl.plot(X, Y, "k.", alpha=0.5)
    # pl.subplot(numplots, 1, numplots-1)
    ax1 = fig4.add_subplot(gs[0])
    # im1 = ax1.imshow(mdl.hebblink_filter, interpolation="none", cmap=pl.get_cmap("gray"))
    im1 = ax1.pcolormesh(hebblink_log, cmap=pl.get_cmap("gray"))
    ax1.set_xlabel("in (e)")
    ax1.set_ylabel("out (p)")
    cbar = fig4.colorbar(mappable = im1, ax=ax1, orientation="horizontal")

    ax2 = fig4.add_subplot(gs[1])

    distarray = np.array(distances)
    print("distarray.shape", distarray.shape)
    pcm = ax2.pcolormesh(distarray.T)
    cbar = fig4.colorbar(mappable = pcm, ax=ax2, orientation="horizontal")

    # pl.subplot(numplots, 1, numplots)
    ax3 = fig4.add_subplot(gs[2])
    actarray = np.array(activities)
    print("actarray.shape", actarray.shape)
    pcm = ax3.pcolormesh(actarray.T)
    cbar = fig4.colorbar(mappable = pcm, ax=ax3, orientation="horizontal")

    ax4 = fig4.add_subplot(gs[3])
    ax4.plot(hebblink_log.flatten())

    print("hebblink_log", hebblink_log)

    fig4.show()
项目:actinf    作者:x75    | 项目源码 | 文件源码
def plot_colormeshmatrix_reduced(
        X, Y, ymin = None, ymax = None,
        title = "plot_colormeshmatrix_reduced"):

    print "plot_colormeshmatrix_reduced X.shape", X.shape, "Y.shape", Y.shape
    # input_cols  = [i for i in df.columns if i.startswith("X")]
    # output_cols = [i for i in df.columns if i.startswith("Y")]
    # Xs = df[input_cols]
    # Ys = df[output_cols]

    # numsamples = df.shape[0]
    # print "plot_scattermatrix_reduced: numsamples = %d" % numsamples

    # # numplots = Xs.shape[1] * Ys.shape[1]
    # # print "numplots = %d" % numplots

    cbar_orientation = "vertical" # "horizontal"
    gs = gridspec.GridSpec(Y.shape[2], X.shape[2]/2)
    pl.ioff()
    fig = pl.figure()
    fig.suptitle(title)
    # # alpha = 1.0 / np.power(numsamples, 1.0/(Xs.shape[1] - 0))
    # alpha = 0.2
    # print "alpha", alpha
    # cols = ["k", "b", "r", "g", "c", "m", "y"]
    for i in range(X.shape[2]/2):
        for j in range(Y.shape[2]):
            # print "i, j", i, j, Xs, Ys
            ax = fig.add_subplot(gs[j, i])
            pcm = ax.pcolormesh(X[:,:,i], X[:,:,X.shape[2]/2+i], Y[:,:,j], vmin = ymin, vmax = ymax)
            # ax.plot(Xs.as_matrix()[:,i], Ys.as_matrix()[:,j], "ko", alpha = alpha)
            ax.set_xlabel("goal")
            ax.set_ylabel("error")
            cbar = fig.colorbar(mappable = pcm, ax=ax, orientation=cbar_orientation)
            ax.set_aspect(1)
    if SAVEPLOTS:
        fig.savefig("fig_%03d_colormeshmatrix_reduced.pdf" % (fig.number), dpi=300)
    fig.show()
项目:SkinLesionNeuralNetwork    作者:Neurality    | 项目源码 | 文件源码
def nice_imshow(ax, data, vmin=None, vmax=None, cmap=None):
    from mpl_toolkits.axes_grid1 import make_axes_locatable
    """Wrapper around pl.imshow"""
    if cmap is None:
        cmap = cm.jet
    if vmin is None:
        vmin = data.min()
    if vmax is None:
        vmax = data.max()
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="5%", pad=0.05)
    im = ax.imshow(data, vmin=vmin, vmax=vmax, interpolation='nearest', cmap=cmap)
    pl.colorbar(im, cax=cax)
项目:deep-learning-experiments    作者:raghakot    | 项目源码 | 文件源码
def nice_imshow(ax, data, vmin=None, vmax=None, cmap=None):
    """Wrapper around pl.imshow"""
    if cmap is None:
        cmap = cm.jet
    if vmin is None:
        vmin = data.min()
    if vmax is None:
        vmax = data.max()
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="5%", pad=0.05)
    im = ax.imshow(data, vmin=vmin, vmax=vmax, interpolation='nearest', cmap=cmap)
    pl.colorbar(im, cax=cax)
项目:Parallel-SGD    作者:angadgill    | 项目源码 | 文件源码
def benchmark(clf_class, params, name):
    print("parameters:", params)
    t0 = time()
    clf = clf_class(**params).fit(X_train, y_train)
    print("done in %fs" % (time() - t0))

    if hasattr(clf, 'coef_'):
        print("Percentage of non zeros coef: %f"
              % (np.mean(clf.coef_ != 0) * 100))
    print("Predicting the outcomes of the testing set")
    t0 = time()
    pred = clf.predict(X_test)
    print("done in %fs" % (time() - t0))

    print("Classification report on test set for classifier:")
    print(clf)
    print()
    print(classification_report(y_test, pred,
                                target_names=news_test.target_names))

    cm = confusion_matrix(y_test, pred)
    print("Confusion matrix:")
    print(cm)

    # Show confusion matrix
    pl.matshow(cm)
    pl.title('Confusion matrix of the %s classifier' % name)
    pl.colorbar()
项目:spyking-circus    作者:spyking-circus    | 项目源码 | 文件源码
def view_classification(data_1, data_2, title=None, save=None):

    fig    = pylab.figure()
    count  = 0
    panels = [0, 2, 1, 3]
    for item in [data_1, data_2]:
        clf, cld, X, X_raw, y = item
        for mode in ['predict', 'decision_function']:
            ax = fig.add_subplot(2, 2, panels[count]+1)

            if mode == 'predict':
                c    = clf
                vmax = 1.0
                vmin = 0.0
            elif mode == 'decision_function':
                c    = cld
                vmax = max(abs(numpy.amin(c)), abs(numpy.amax(c)))
                vmin = - vmax

            from circus.validating.utils import Projection
            p = Projection()
            _ = p.fit(X_raw, y)
            X_raw_ = p.transform(X_raw)
            # Plot figure.
            sc = ax.scatter(X_raw_[:, 0], X_raw_[:, 1], c=c, s=5, lw=0.1, cmap='bwr',
                            vmin=vmin, vmax=vmax)
            cb = fig.colorbar(sc)
            ax.grid(True)
            if panels[count] in [0, 1]:
                if panels[count] == 0:
                    ax.set_title('Classification Before')
                    ax.set_ylabel("2nd component")
                if panels[count] == 1:
                    ax.set_title('Classification After')
                    cb.set_label('Prediction')
            elif panels[count] in [2, 3]:
                ax.set_xlabel("1st component")
                if panels[count] == 2:
                    ax.set_ylabel("2nd component")
                if panels[count] == 3:
                    cb.set_label('Decision function')
            count += 1

    if save is None:
        pylab.show()
    else:
        pylab.savefig(save)
        pylab.close(fig)
    return
项目:smp_base    作者:x75    | 项目源码 | 文件源码
def plot_hebbsom_links_distances_activations(X, Y, mdl, predictions, distances, activities, saveplot = False):
    """plot the hebbian link matrix, and all node distances and activities for all inputs"""


    hebblink_log = np.log(mdl.hebblink_filter.T + 1.0)

    fig = pl.figure()
    fig.suptitle("Debugging SOM: hebbian links, distances, activities (%s)" % (mdl.__class__.__name__))
    gs = gridspec.GridSpec(4, 1)
    # pl.plot(X, Y, "k.", alpha=0.5)
    # pl.subplot(numplots, 1, numplots-1)
    ax1 = fig.add_subplot(gs[0])
    ax1.set_title('hebbian associative links')
    # im1 = ax1.imshow(mdl.hebblink_filter, interpolation="none", cmap=pl.get_cmap("gray"))
    im1 = ax1.pcolormesh(hebblink_log, cmap=pl.get_cmap("gray"))
    ax1.set_xlabel("in (e)")
    ax1.set_ylabel("out (p)")
    cbar = fig.colorbar(mappable = im1, ax=ax1, orientation="horizontal")

    ax2 = fig.add_subplot(gs[1])
    ax2.set_title('distances over time')

    distarray = np.array(distances)
    # print("distarray.shape", distarray.shape)
    pcm = ax2.pcolormesh(distarray.T)
    cbar = fig.colorbar(mappable = pcm, ax=ax2, orientation="horizontal")

    # pl.subplot(numplots, 1, numplots)
    ax3 = fig.add_subplot(gs[2])
    ax3.set_title('activations propagated via hebbian links')
    actarray = np.array(activities)
    # print("actarray.shape", actarray.shape)
    pcm = ax3.pcolormesh(actarray.T)
    cbar = fig.colorbar(mappable = pcm, ax=ax3, orientation="horizontal")

    ax4 = fig.add_subplot(gs[3])
    ax4.set_title('flattened link table')
    ax4.plot(hebblink_log.flatten())

    # print("hebblink_log", hebblink_log)

    if saveplot:
        filename = "plot_hebbsom_links_distances_activations_%s.jpg" % (mdl.__class__.__name__,)
        savefig(fig, filename)
    fig.show()
项目:chainer-speech-recognition    作者:musyoku    | 项目源码 | 文件源码
def _plot_features(out_dir, signal, sampling_rate, logmel, delta, delta_delta, specgram, filename):
    try:
        os.makedirs(out_dir)
    except:
        pass

    sampling_interval = 1.0 / sampling_rate
    times = np.arange(len(signal)) * sampling_interval
    pylab.clf()
    plt.rcParams['font.size'] = 18
    pylab.figure(figsize=(len(signal) / 2000, 16)) 

    ax1 = pylab.subplot(511)
    pylab.plot(times, signal)
    pylab.title("Waveform")
    pylab.xlabel("Time [sec]")
    pylab.ylabel("Amplitude")
    pylab.xlim([0, len(signal) * sampling_interval])

    ax2 = pylab.subplot(512)
    specgram = np.log(specgram)
    pylab.pcolormesh(np.arange(0, specgram.shape[0]), np.arange(0, specgram.shape[1]) * 8000 / specgram.shape[1], specgram.T, cmap=pylab.get_cmap("jet"))
    pylab.title("Spectrogram")
    pylab.xlabel("Time [sec]")
    pylab.ylabel("Frequency [Hz]")
    pylab.colorbar()

    ax3 = pylab.subplot(513)
    pylab.pcolormesh(np.arange(0, logmel.shape[0]), np.arange(1, 41), logmel.T, cmap=pylab.get_cmap("jet"))
    pylab.title("Log mel filter bank features")
    pylab.xlabel("Frame")
    pylab.ylabel("Filter number")
    pylab.colorbar()

    ax4 = pylab.subplot(514)
    pylab.pcolormesh(np.arange(0, delta.shape[0]), np.arange(1, 41), delta.T, cmap=pylab.get_cmap("jet"))
    pylab.title("Deltas")
    pylab.xlabel("Frame")
    pylab.ylabel("Filter number")
    pylab.colorbar()

    ax5 = pylab.subplot(515)
    pylab.pcolormesh(np.arange(0, delta_delta.shape[0]), np.arange(1, 41), delta_delta.T, cmap=pylab.get_cmap("jet"))
    pylab.title("Delta-deltas")
    pylab.xlabel("Frame")
    pylab.ylabel("Filter number")
    pylab.colorbar()

    pylab.tight_layout()
    pylab.savefig(os.path.join(out_dir, filename), bbox_inches="tight")
项目:emc_and_dm    作者:eucall-software    | 项目源码 | 文件源码
def make_mutual_info_plot(fn):
    M.rcParams.update({'font.size': 11})
    angleList = N.array([f/f.max() for f in read.extract_arr_from_h5(fn, "/history/angle", n=-1)])
    mutualInfoList = read.extract_arr_from_h5(fn, "/history/mutual_info", n=-1)
    quatList = read.extract_arr_from_h5(fn, "/history/quaternion", n=-1)
    quatSwitchPos = N.where(quatList[:-1]-quatList[1:] != 0)[0] + 1
    angsort = N.argsort(angleList[-1])
    misort = N.argsort(mutualInfoList.mean(axis=0))
    blkPositions = [0] + list(quatSwitchPos) + [-1]
    for bp in range(len(blkPositions)-1):
        (start, end) = (blkPositions[bp], blkPositions[bp+1])
        curr_blk = angleList[start:end]
        curr_blk2 = mutualInfoList[start:end] / N.log(quatSize[quatList[0]])
        # curr_blk2 = mutualInfoList[start:end] / N.log(quatSize[quatList[bp]])
        if len(curr_blk) == 0:
            pass
        else:
            angsort = N.argsort(curr_blk[-1])
            angleList[start:end] = curr_blk[:,angsort]
            for n,l in enumerate(curr_blk2):
                misort = N.argsort(l)
                mutualInfoList[start+n] = l[misort]

    P.ioff()
    fig, ax = P.subplots(2, 1, sharex=True, figsize=(7, 10))
    fig.subplots_adjust(hspace=0.1)
    im0 = ax[0].imshow(angleList.transpose(), aspect='auto', interpolation=None, cmap=P.cm.OrRd)
    ax[0].set_xlabel("iteration")
    ax[0].set_ylabel("each pattern's most likely orientation\n(sorted by final orientation in each block)")
    (e_min, e_max) = (1, len(angleList[0]))
    e_int = 0.1*(e_max-e_min)
    ax[0].plot([0, 0], [e_min, e_max], 'k-')
    ax[0].text(1, e_max-e_int, "quat%d"%quatList[0], size=8, rotation=-0, ha='left', va='center', color='w', bbox=dict(boxstyle="larrow,pad=0.1",facecolor='0.1') )
    for n,qs in enumerate(quatSwitchPos):
        ax[0].plot([qs, qs], [e_min, e_max], 'k-')
        ax[0].text(qs-1, e_max+(-n-1)*e_int, "quat%d"%quatList[qs], size=8, rotation=-0, ha='right', va='center', color='w', bbox=dict(boxstyle="rarrow,pad=0.1",facecolor='0.1') )
    div0 = make_axes_locatable(ax[0])
    cax0 = div0.append_axes("right", size="5%", pad=0.05)
    cbar0 = P.colorbar(im0, cax=cax0)
    ax[0].set_ylim(e_min, e_max)
    ax[0].set_xlim(0, len(angleList)-1)

    (e_min, e_max) = (1, len(mutualInfoList[0]))
    e_int = 0.1*(e_max-e_min)
    im1 = ax[1].imshow(mutualInfoList.transpose(), vmax=.2, aspect='auto', cmap=P.cm.YlGnBu)
    ax[1].set_xlabel("iteration")
    ax[1].set_ylabel("average mutual-information per dataset\n(sorted by average information)")
    ax[1].plot([0, 0], [e_min, e_max], 'k-')
    ax[1].text(1, e_max-e_int, "quat%d"%quatList[0], size=8, rotation=-0, ha='left', va='center', color='w', bbox=dict(boxstyle="larrow,pad=0.1",facecolor='0.1') )
    for n,qs in enumerate(quatSwitchPos):
        ax[1].plot([qs, qs], [e_min, e_max], 'k-')
        ax[1].text(qs-1, e_max+(-n-1)*e_int, "quat%d"%quatList[qs], size=8, rotation=-0, ha='right', va='center', color='w', bbox=dict(boxstyle="rarrow,pad=0.1",facecolor='0.1') )
    div1 = make_axes_locatable(ax[1])
    cax1 = div1.append_axes("right", size="5%", pad=0.05)
    cbar1 = P.colorbar(im1, cax=cax1)
    ax[1].set_ylim(e_min, e_max)
    ax[1].set_xlim(0, len(mutualInfoList)-1)
    img_name = "mutual_info_plot.pdf"
    P.savefig(img_name, bbox_inches='tight')
    print("Image has been saved as %s" % img_name)
    P.close(fig)
项目:ugali    作者:DarkEnergySurvey    | 项目源码 | 文件源码
def densityPlot(targ_ra, targ_dec, data, iso, g_radius, nbhd, type):
    """Stellar density plot"""

    mag_g = data[mag_g_dred_flag]
    mag_r = data[mag_r_dred_flag]

    if type == 'stars':
        filter = star_filter(data)
        plt.title('Stellar Density')
    elif type == 'galaxies':
        filter = galaxy_filter(data)
        plt.title('Galactic Density')
    elif type == 'blue_stars':
        filter = blue_star_filter(data)
        plt.title('Blue Stellar Density')

    iso_filter = (iso.separation(mag_g, mag_r) < 0.1)

    # projection of image
    proj = ugali.utils.projector.Projector(targ_ra, targ_dec)
    x, y = proj.sphereToImage(data[filter & iso_filter]['RA'], data[filter & iso_filter]['DEC']) # filter & iso_filter

    bound = 0.5 #1.
    steps = 100.
    bins = np.linspace(-bound, bound, steps)

    signal = np.histogram2d(x, y, bins=[bins, bins])[0]

    sigma = 0.01 * (0.25 * np.arctan(0.25*g_radius*60. - 1.5) + 1.3) # full range, arctan

    convolution = scipy.ndimage.filters.gaussian_filter(signal, sigma/(bound/steps))
    plt.pcolormesh(bins, bins, convolution.T, cmap='Greys')

    plt.xlim(bound, -bound)
    plt.ylim(-bound, bound)
    plt.gca().set_aspect('equal')
    plt.xlabel(r'$\Delta \alpha$ (deg)')
    plt.ylabel(r'$\Delta \delta$ (deg)')

    ax = plt.gca()
    divider = make_axes_locatable(ax)
    cax = divider.append_axes('right', size = '5%', pad=0)
    plt.colorbar(cax=cax)
项目:ugali    作者:DarkEnergySurvey    | 项目源码 | 文件源码
def hessPlot(targ_ra, targ_dec, data, iso, g_radius, nbhd):
    """Hess plot"""

    mag_g = data[mag_g_dred_flag]
    mag_r = data[mag_r_dred_flag]

    filter_s = star_filter(data)

    plt.title('Hess')

    c1 = SkyCoord(targ_ra, targ_dec, unit='deg')

    r_near = 2.*g_radius # annulus begins at 3*g_radius away from centroid
    r_far = np.sqrt(5.)*g_radius # annulus has same area as inner area

    inner = (c1.separation(SkyCoord(data['RA'], data['DEC'], unit='deg')).deg < g_radius)
    outer = (c1.separation(SkyCoord(data['RA'], data['DEC'], unit='deg')).deg > r_near) & (c1.separation(SkyCoord(data['RA'], data['DEC'], unit='deg')).deg < r_far)

    xbins = np.arange(-0.5, 1.1, 0.1)
    ybins = np.arange(16., 24.5, 0.5)

    foreground = np.histogram2d(mag_g[inner & filter_s] - mag_r[inner & filter_s], mag_g[inner & filter_s], bins=[xbins, ybins])
    background = np.histogram2d(mag_g[outer & filter_s] - mag_r[outer & filter_s], mag_g[outer & filter_s], bins=[xbins, ybins])

    fg = foreground[0].T
    bg = background[0].T

    fg_abs = np.absolute(fg)
    bg_abs = np.absolute(bg)

    mask_abs = fg_abs + bg_abs
    mask_abs[mask_abs == 0.] = np.nan # mask signficiant zeroes

    signal = fg - bg
    signal = np.ma.array(signal, mask=np.isnan(mask_abs)) # mask nan

    cmap = matplotlib.cm.viridis
    cmap.set_bad('w', 1.)
    plt.pcolormesh(xbins, ybins, signal, cmap=cmap)

    plt.colorbar()

    ugali.utils.plotting.drawIsochrone(iso, lw=2, c='k', zorder=10, label='Isocrhone')

    plt.axis([-0.5, 1.0, 16, 24])
    plt.gca().invert_yaxis()
    plt.gca().set_aspect(1./4.)
    plt.xlabel('g-r (mag)')
    plt.ylabel('g (mag)')

    #ax = plt.gca()
    #divider = make_axes_locatable(ax)
    #cax = divider.append_axes('right', size = '5%', pad=0)
    #plt.colorbar(cax=cax)
项目:ugali    作者:DarkEnergySurvey    | 项目源码 | 文件源码
def drawMembership(self, ax=None, radius=None, zidx=0, mc_source_id=1):
        if not ax: ax = plt.gca()
        import ugali.analysis.scan

        filename = self.config.mergefile
        logger.debug("Opening %s..."%filename)
        f = pyfits.open(filename)
        distance_modulus = f[2].data['DISTANCE_MODULUS'][zidx]

        for ii, name in enumerate(self.config.params['isochrone']['infiles']):
            logger.info('%s %s'%(ii, name))
            isochrone = ugali.isochrone.Isochrone(self.config, name)
            mag = isochrone.mag + distance_modulus
            ax.scatter(isochrone.color,mag, color='0.5', s=800, zorder=0)


        pix = ang2pix(self.nside, self.glon, self.glat)
        likelihood_pix = ugali.utils.skymap.superpixel(pix,self.nside,self.config.params['coords']['nside_likelihood'])
        config = self.config
        scan = ugali.analysis.scan.Scan(self.config,likelihood_pix)
        likelihood = scan.likelihood
        distance_modulus_array = [self.config.params['scan']['distance_modulus_array'][zidx]]
        likelihood.precomputeGridSearch(distance_modulus_array)
        likelihood.gridSearch()
        p = likelihood.membershipGridSearch()

        sep = ugali.utils.projector.angsep(self.glon, self.glat, likelihood.catalog.lon, likelihood.catalog.lat)
        radius = self.radius if radius is None else radius
        cut = (sep < radius)
        catalog = likelihood.catalog.applyCut(cut)
        p = p[cut]

        cut_mc_source_id = (catalog.mc_source_id == mc_source_id)
        ax.scatter(catalog.color[cut_mc_source_id], catalog.mag[cut_mc_source_id], c='gray', s=100, edgecolors='none')
        sc = ax.scatter(catalog.color, catalog.mag, c=p, edgecolors='none')

        ax.set_xlim(likelihood.roi.bins_color[0], likelihood.roi.bins_color[-1])
        ax.set_ylim(likelihood.roi.bins_mag[-1], likelihood.roi.bins_mag[0])
        ax.set_xlabel('Color (mag)')
        ax.set_ylabel('Magnitude (mag)')
        try: ax.cax.colorbar(sc)
        except: pylab.colorbar(sc)
项目:ugali    作者:DarkEnergySurvey    | 项目源码 | 文件源码
def plotDistance(self):
        filename = self.config.mergefile
        logger.debug("Opening %s..."%filename)
        f = pyfits.open(filename)
        pixels,values = f[1].data['PIXEL'],2*f[1].data['LOG_LIKELIHOOD']
        if values.ndim == 1: values = values.reshape(-1,1)
        distances = f[2].data['DISTANCE_MODULUS']
        if distances.ndim == 1: distances = distances.reshape(-1,1)
        ts_map = healpy.UNSEEN * numpy.ones(healpy.nside2npix(self.nside))

        ndim = len(distances)
        nrows = int(numpy.sqrt(ndim))
        ncols = ndim // nrows + (ndim%nrows > 0)

        fig = pylab.figure()
        axes  = AxesGrid(fig, 111, nrows_ncols = (nrows, ncols),axes_pad=0,
                         label_mode='1', cbar_mode='single',cbar_pad=0,cbar_size='5%',
                         share_all=True,add_all=False)

        images = []
        for i,val in enumerate(values.T):
            ts_map[pixels] = val

            im = healpy.gnomview(ts_map,**self.gnom_kwargs)
            pylab.close()
            images.append(im)
        data = numpy.array(images); mask = (data == healpy.UNSEEN)
        images = numpy.ma.array(data=data,mask=mask)
        vmin = numpy.ma.min(images)
        vmax = numpy.ma.max(images)

        for i,val in enumerate(values.T):
            ax = axes[i]
            im = ax.imshow(images[i],origin='bottom',vmin=vmin,vmax=vmax)
            ax.cax.colorbar(im)

            #ax.annotate(r"$\mu = %g$"%distances[i],**self.label_kwargs)
            ax.annotate(r"$d = %.0f$ kpc"%mod2dist(distances[i]),**self.label_kwargs)
            ax.axis["left"].major_ticklabels.set_visible(False) 
            ax.axis["bottom"].major_ticklabels.set_visible(False) 
            fig.add_axes(ax)
            fig.add_axes(ax.cax)
        return fig,axes
项目:ugali    作者:DarkEnergySurvey    | 项目源码 | 文件源码
def drawKernelHist(ax, kernel):
    ext = kernel.extension
    theta = kernel.theta
    lon, lat = kernel.lon, kernel.lat
    xmin,xmax = -5*ext,5*ext
    ymin,ymax = -5*ext,5*ext,
    x = np.linspace(xmin,xmax,100)+kernel.lon
    y = np.linspace(ymin,ymax,100)+kernel.lat

    xx,yy = np.meshgrid(x,y)
    zz = kernel.pdf(xx,yy)
    im = ax.imshow(zz)#,extent=[xmin,xmax,ymin,ymax])
    hax,vax = draw_slices(ax,zz,color='k')

    mc_lon,mc_lat = kernel.sample(1e5)
    hist,xedges,yedges = np.histogram2d(mc_lon,mc_lat,bins=[len(x),len(y)],
                                        range=[[x.min(),x.max()],[y.min(),y.max()]])
    xbins,ybins = np.arange(hist.shape[0])+0.5,np.arange(hist.shape[1])+0.5

    vzz = zz.sum(axis=0)
    hzz = zz.sum(axis=1)
    vmc = hist.sum(axis=0)
    hmc = hist.sum(axis=1)

    vscale = vzz.max()/vmc.max()
    hscale = hzz.max()/hmc.max()

    kwargs = dict(marker='.',ls='',color='r')
    hax.errorbar(hmc*hscale, ybins, xerr=np.sqrt(hmc)*hscale,**kwargs)
    vax.errorbar(xbins, vmc*vscale,yerr=np.sqrt(vmc)*vscale,**kwargs) 

    ax.set_ylim(0,len(y))
    ax.set_xlim(0,len(x))

    #try: ax.cax.colorbar(im)
    #except: pylab.colorbar(im)

    #a0 = np.array([0.,0.])
    #a1 =kernel.a*np.array([np.sin(np.deg2rad(theta)),-np.cos(np.deg2rad(theta))])
    #ax.plot([a0[0],a1[0]],[a0[1],a1[1]],'-ob')
    # 
    #b0 = np.array([0.,0.])
    #b1 =kernel.b*np.array([np.cos(np.radians(theta)),np.sin(np.radians(theta))])
    #ax.plot([b0[0],b1[0]],[b0[1],b1[1]],'-or')    

    label_kwargs = dict(xy=(0.05,0.05),xycoords='axes fraction', xytext=(0, 0), 
                        textcoords='offset points',ha='left', va='bottom',size=10,
                        bbox={'boxstyle':"round",'fc':'1'}, zorder=10)
    norm = zz.sum() * (x[1]-x[0])**2
    ax.annotate("Sum = %.2f"%norm,**label_kwargs)

    #ax.set_xlabel(r'$\Delta$ LON (deg)')
    #ax.set_ylabel(r'$\Delta$ LAT (deg)')

###################################################
项目:ugali    作者:DarkEnergySurvey    | 项目源码 | 文件源码
def satellitePopulation(config, n,
                        range_distance_modulus=[16.5, 24.],
                        range_stellar_mass=[1.e2, 1.e5],
                        mode='mask',
                        plot=False):
    """
    Create a population of n randomly placed satellites within a survey mask or catalog specified in the config file.
    Satellites are uniformly placed in distance modulus, and uniformly generated in log(stellar_mass) (M_sol).
    The ranges can be set by the user.

    Returns the simulated area (deg^2) as well as the
    lon (deg), lat (deg), distance modulus, stellar mass (M_sol), and half-light radius (deg) for each satellite
    """

    if type(config) == str:
        config = ugali.utils.config.Config(config)

    if mode == 'mask':
        mask_1 = ugali.utils.skymap.readSparseHealpixMap(config.params['mask']['infile_1'], 'MAGLIM')
        mask_2 = ugali.utils.skymap.readSparseHealpixMap(config.params['mask']['infile_2'], 'MAGLIM')
        input = (mask_1 > 0.) * (mask_2 > 0.)
    elif mode == 'catalog':
        catalog = ugali.observation.catalog.Catalog(config)
        input = numpy.array([catalog.lon, catalog.lat])

    lon, lat, simulation_area = ugali.utils.skymap.randomPositions(input,
                                                                   config.params['coords']['nside_likelihood_segmentation'],
                                                                   n=n)
    distance_modulus = numpy.random.uniform(range_distance_modulus[0], range_distance_modulus[1], n)
    stellar_mass = 10**numpy.random.uniform(numpy.log10(range_stellar_mass[0]), numpy.log10(range_stellar_mass[1]), n)
    half_light_radius_physical = ugali.analysis.kernel.halfLightRadius(stellar_mass) # kpc
    half_light_radius = numpy.degrees(numpy.arcsin(half_light_radius_physical \
                                                   / ugali.utils.projector.distanceModulusToDistance(distance_modulus)))

    if plot:
        pylab.figure()
        #pylab.scatter(lon, lat, c=distance_modulus, s=500 * half_light_radius)
        #pylab.colorbar()
        pylab.scatter(lon, lat, edgecolors='none')
        xmin, xmax = pylab.xlim() # Reverse azimuthal axis
        pylab.xlim([xmax, xmin])
        pylab.title('Random Positions in Survey Footprint')
        pylab.xlabel('Longitude (deg)')
        pylab.ylabel('Latitude (deg)')

        pylab.figure()
        pylab.scatter(stellar_mass, ugali.utils.projector.distanceModulusToDistance(distance_modulus),
                      c=(60. * half_light_radius), s=500 * half_light_radius, edgecolors='none')
        pylab.xscale('log')
        pylab.yscale('log')
        pylab.xlim([0.5 * range_stellar_mass[0], 2. * range_stellar_mass[1]])
        pylab.colorbar()
        pylab.title('Half-light Radius (arcmin)')
        pylab.xlabel('Stellar Mass (arcmin)')
        pylab.ylabel('Distance (kpc)')

    return simulation_area, lon, lat, distance_modulus, stellar_mass, half_light_radius 

############################################################
项目:PyMaid    作者:schlegelp    | 项目源码 | 文件源码
def plot_matrix(self):
        """ Plot distance matrix and dendrogram using matplotlib.

        Returns
        -------
        matplotlib figure
        """

        # Compute and plot first dendrogram for all nodes.
        fig = pylab.figure(figsize=(8, 8))
        ax1 = fig.add_axes([0.09, 0.1, 0.2, 0.6])
        Z1 = scipy.cluster.hierarchy.dendrogram(
            self.linkage, orientation='left', labels=self.labels)
        ax1.set_xticks([])
        ax1.set_yticks([])

        # Compute and plot second dendrogram.
        ax2 = fig.add_axes([0.3, 0.71, 0.6, 0.2])
        Z2 = scipy.cluster.hierarchy.dendrogram(self.linkage, labels=self.labels)
        ax2.set_xticks([])
        ax2.set_yticks([])

        # Plot distance matrix.
        axmatrix = fig.add_axes([0.3, 0.1, 0.6, 0.6])
        idx1 = Z1['leaves']
        idx2 = Z2['leaves']
        D = self.mat.copy()

        if isinstance(D, pd.DataFrame):
            D = D.as_matrix()

        D = D[idx1, :]
        D = D[:, idx2]
        im = axmatrix.matshow(
            D, aspect='auto', origin='lower', cmap=pylab.cm.YlGnBu)
        axmatrix.set_xticks([])
        axmatrix.set_yticks([])

        # Plot colorbar.
        axcolor = fig.add_axes([0.91, 0.1, 0.02, 0.6])
        pylab.colorbar(im, cax=axcolor)

        module_logger.info(
            'Use matplotlib.pyplot.show() to render figure.')

        return fig