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

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

项目: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
项目:office-interoperability-tools    作者:milossramek    | 项目源码 | 文件源码
def disp(iimg, label = "", gray=False):
    """ Display an image using pylab
    """
    try:
        import pylab
        dimage = iimg.copy()
        if iimg.ndim==3:
            dimage[...,0] = iimg[...,2]
            dimage[...,2] = iimg[...,0]

        pylab.imshow(dimage, interpolation='none')
        if gray: pylab.gray()
        #pylab.gca().format_coord = format_coord
        pylab.text(1500, -30, label)
        pylab.axis('off')
        pylab.show()
    except ImportError:
        print "Module pylab not available"
项目:facade-segmentation    作者:jfemiani    | 项目源码 | 文件源码
def plot_regions(self, fill=True, bgimage=None, alpha=0.5):
        import pylab as pl
        ax = pl.gca()
        assert isinstance(ax, pl.Axes)

        colors = i12.JET_12

        self._plot_background(bgimage)

        for label in self.regions:
            color = colors[i12.LABELS.index(label)] / 255.

            for region in self.regions[label]:
                t = region['top']
                l = self.facade_left + region['left']
                b = region['bottom']
                r = self.facade_left + region['right']
                patch = pl.Rectangle((l, t), r - l, b - t, color=color, fill=fill, alpha=alpha)
                ax.add_patch(patch)
项目:GLaDOS2    作者:TheComet    | 项目源码 | 文件源码
def plot_word_frequencies(freq, user):
        samples = [item for item, _ in freq.most_common(50)]

        freqs = np.array([float(freq[sample]) for sample in samples])
        freqs /= np.max(freqs)

        ylabel = "Normalized word count"

        pylab.grid(True, color="silver")
        kwargs = dict()
        kwargs["linewidth"] = 2
        kwargs["label"] = user
        pylab.plot(freqs, **kwargs)
        pylab.xticks(range(len(samples)), [nltk.compat.text_type(s) for s in samples], rotation=90)
        pylab.xlabel("Samples")
        pylab.ylabel(ylabel)
        pylab.gca().set_yscale('log', basey=2)
项目:tap    作者:mfouesneau    | 项目源码 | 文件源码
def hide_axis(where, ax=None):
    ax = ax or plt.gca()
    if type(where) == str:
        _w = [where]
    else:
        _w = where
    [sk.set_color('None') for k, sk in ax.spines.items() if k in _w ]

    if 'top' in _w and 'bottom' in _w:
        ax.xaxis.set_ticks_position('none')
    elif 'top' in _w:
        ax.xaxis.set_ticks_position('bottom')
    elif 'bottom' in _w:
        ax.xaxis.set_ticks_position('top')

    if 'left' in _w and 'right' in _w:
        ax.yaxis.set_ticks_position('none')
    elif 'left' in _w:
        ax.yaxis.set_ticks_position('right')
    elif 'right' in _w:
        ax.yaxis.set_ticks_position('left')

    plt.draw_if_interactive()
项目:tap    作者:mfouesneau    | 项目源码 | 文件源码
def shift_axis(which, delta, where='outward', ax=None):
    ax = ax or plt.gca()
    if type(which) == str:
        _w = [which]
    else:
        _w = which

    scales = (ax.xaxis.get_scale(), ax.yaxis.get_scale())
    lbls = (ax.xaxis.get_label(), ax.yaxis.get_label())

    for wk in _w:
        ax.spines[wk].set_position((where, delta))

    ax.set_xscale(scales[0])
    ax.set_yscale(scales[1])
    ax.xaxis.set_label(lbls[0])
    ax.yaxis.set_label(lbls[1])
    plt.draw_if_interactive()
项目:tap    作者:mfouesneau    | 项目源码 | 文件源码
def setNmajors(xval=None, yval=None, ax=None, mode='auto', **kwargs):
        """
        setNmajors - set major tick number
        see figure.MaxNLocator for kwargs
        """
        if ax is None:
                ax = plt.gca()
        if (mode == 'fixed'):
                if xval is not None:
                        ax.xaxis.set_major_locator(MaxNLocator(xval, **kwargs))
                if yval is not None:
                        ax.yaxis.set_major_locator(MaxNLocator(yval, **kwargs))
        elif (mode == 'auto'):
                if xval is not None:
                        ax.xaxis.set_major_locator(AutoLocator(xval, **kwargs))
                if yval is not None:
                        ax.yaxis.set_major_locator(AutoLocator(yval, **kwargs))

        plt.draw_if_interactive()
项目:tap    作者:mfouesneau    | 项目源码 | 文件源码
def error_ellipse(mu, cov, ax=None, factor=1.0, **kwargs):
    """
    Plot the error ellipse at a point given its covariance matrix.

    """
    # some sane defaults
    facecolor = kwargs.pop('facecolor', 'none')
    edgecolor = kwargs.pop('edgecolor', 'k')

    x, y = mu
    U, S, V = np.linalg.svd(cov)
    theta = np.degrees(np.arctan2(U[1, 0], U[0, 0]))
    ellipsePlot = Ellipse(xy=[x, y],
                          width=2 * np.sqrt(S[0]) * factor,
                          height=2 * np.sqrt(S[1]) * factor,
                          angle=theta,
                          facecolor=facecolor, edgecolor=edgecolor, **kwargs)

    if ax is None:
        ax = plt.gca()
    ax.add_patch(ellipsePlot)

    return ellipsePlot
项目:ugali    作者:DarkEnergySurvey    | 项目源码 | 文件源码
def starPlot(targ_ra, targ_dec, data, iso, g_radius, nbhd):
    """Star bin plot"""

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

    filter = star_filter(data)

    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'])

    plt.scatter(x, y, edgecolor='none', s=3, c='black')
    plt.xlim(0.2, -0.2)
    plt.ylim(-0.2, 0.2)
    plt.gca().set_aspect('equal')
    plt.xlabel(r'$\Delta \alpha$ (deg)')
    plt.ylabel(r'$\Delta \delta$ (deg)')

    plt.title('Stars')
项目:ugali    作者:DarkEnergySurvey    | 项目源码 | 文件源码
def drawSmoothCatalog(self, catalog, label=None, **kwargs):
        ax = plt.gca()
        ra,dec = catalog.ra_dec
        x, y = sphere2image(self.ra,self.dec,ra,dec)

        delta_x = self.radius/100.
        smoothing = 2*delta_x
        bins = numpy.arange(-self.radius, self.radius + 1.e-10, delta_x)
        h, xbins, ybins = numpy.histogram2d(x, y, bins=[bins, bins])
        blur = nd.filters.gaussian_filter(h.T, smoothing / delta_x)

        defaults = dict(cmap='gray_r',rasterized=True)
        kwargs = dict(defaults.items()+kwargs.items())

        xx,yy = np.meshgrid(xbins,ybins)
        im = drawProjImage(xx,yy,blur,coord='C',**kwargs)

        if label:
            plt.text(0.05, 0.95, label, fontsize=10, ha='left', va='top', 
                     color='k', transform=pylab.gca().transAxes,
                     bbox=dict(facecolor='white', alpha=1., edgecolor='none'))
项目:ugali    作者:DarkEnergySurvey    | 项目源码 | 文件源码
def drawROI(self, ax=None, value=None, pixel=None):
        if not ax: ax = plt.gca()
        roi_map = np.array(healpy.UNSEEN*np.ones(healpy.nside2npix(self.nside)))

        if value is None:
            roi_map[self.roi.pixels] = 1
            roi_map[self.roi.pixels_annulus] = 0
            roi_map[self.roi.pixels_target] = 2
        elif value is not None and pixel is None:
            roi_map[self.pixels] = value
        elif value is not None and pixel is not None:
            roi_map[pixel] = value
        else:
            logger.warning('Unable to parse input')
        #im = healpy.gnomview(roi_map,**self.gnom_kwargs)
        im = drawHealpixMap(roi_map,self.glon,self.glat,self.radius,coord=self.coord)
        return im
项目: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
项目:ugali    作者:DarkEnergySurvey    | 项目源码 | 文件源码
def drawMask(self,ax=None, mask=None):
        if not ax: ax = plt.gca()
        # MAGLIM Mask
        if mask is None:
            filenames = self.config.getFilenames()
            catalog_pixels = self.roi.getCatalogPixels()
            mask_map = ugali.utils.skymap.readSparseHealpixMaps(filenames['mask_1'][catalog_pixels], field='MAGLIM')
        else:
            mask_map = healpy.UNSEEN*np.ones(healpy.nside2npix(self.config['coords']['nside_pixel']))
            mask_map[mask.roi.pixels] = mask.mask_1.mask_roi_sparse
        mask_map = numpy.where(mask_map == healpy.UNSEEN, 0, mask_map)

        #im = healpy.gnomview(mask_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(mask_map,self.glon,self.glat,self.radius,coord=self.coord)

        try: ax.cax.colorbar(im)
        except: pylab.colorbar(im)
        ax.annotate("Mask",**self.label_kwargs)
        return im
项目:spyking-circus-ort    作者:spyking-circus    | 项目源码 | 文件源码
def _plot(self):
        # Called from the main thread
        pylab.ion()

        if not getattr(self, 'data_available', False):
            return

        if self.peaks is not None:

            for key in self.sign_peaks:
                for channel in self.peaks[key].keys():
                    self.rates[key][int(channel)] += len(self.peaks[key][channel])

            pylab.scatter(self.positions[0, :], self.positions[1, :], c=self.rates[key])

        pylab.gca().set_title('Buffer %d' %self.counter)
        pylab.draw()
        return
项目:PyPeVoc    作者:goiosunsw    | 项目源码 | 文件源码
def plot(self, logarithmic=False):
        """Plot a graphical representation of the peaks

        Arguments:
            (none)
        """

        import pylab as pl

        pl.figure()
        pl.plot(self.x)
        pl.hold('on')
        pl.plot(self.pos[self.keep], self.val[self.keep], 'og')
        pl.plot(self.pos[np.logical_not(self.keep)],
                self.val[np.logical_not(self.keep)], 'om')
        if hasattr(self, 'bounds'):
            lmins = np.unique(self.bounds.flatten())
            lminvals = self.x[lmins]
            pl.plot(lmins, lminvals, 'or')
        if hasattr(self, 'fpos'):
            pl.plot(self.fpos[self.keep], self.fval[self.keep], 'dg')
        pl.hold('off')
        if logarithmic:
            pl.gca().set_yscale('log')
项目: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()
项目:PyPeVoc    作者:goiosunsw    | 项目源码 | 文件源码
def two_plot_time_freq_mag(self, minlen=10):
        part = [pp for pp in self.partial if len(pp.f) > minlen]
        pl.figure()
        ax1 = pl.subplot(211)
        pl.hold(True)
        ax2 = pl.subplot(212, sharex=ax1)
        pl.hold(True)
        for pp in part:
            ax1.plot(pp.start_idx + np.arange(len(pp.f)), np.array(pp.f))
            ax2.plot(pp.start_idx + np.arange(len(pp.f)),
                     20*np.log10(np.array(pp.mag)))
        ax1.hold(False)
        # ax1.xlabel('Time (s)')
        ax1.set_ylabel('Frequency (Hz)')
        ax2.set_xlabel('Time (s)')
        ax2.set_ylabel('Frequency (Hz)')
        # pl.show()
        return pl.gca()
项目:bokeh_roc_slider    作者:brianray    | 项目源码 | 文件源码
def plot_multiple_rocs_separate(rocList,title='', labels = None, equal_aspect = True):
    """ Plot multiples ROC curves as separate at the same painting area. """
    pylab.clf()
    pylab.title(title)
    for ix, r in enumerate(rocList):
        ax = pylab.subplot(4,4,ix+1)
        pylab.ylim((0,1))
        pylab.xlim((0,1))
        ax.set_yticklabels([])
        ax.set_xticklabels([])
        if equal_aspect:
            cax = pylab.gca()
            cax.set_aspect('equal')

        if not labels:
            labels = ['' for x in rocList]

        pylab.text(0.2,0.1,labels[ix],fontsize=8)
        pylab.plot([x[0] for x in r.derived_points],[y[1] for y in r.derived_points], 'r-',linewidth=2)

    pylab.show()
项目:bokeh_roc_slider    作者:brianray    | 项目源码 | 文件源码
def plot(self,title='',include_baseline=False,equal_aspect=True):
        """ Method that generates a plot of the ROC curve
            Parameters:
                title: Title of the chart
                include_baseline: Add the baseline plot line if it's True
                equal_aspect: Aspects to be equal for all plot
        """

        pylab.clf()
        pylab.plot([x[0] for x in self.derived_points], [y[1] for y in self.derived_points], self.linestyle)
        if include_baseline:
            pylab.plot([0.0,1.0], [0.0,1.0],'k-.')
        pylab.ylim((0,1))
        pylab.xlim((0,1))
        pylab.xticks(pylab.arange(0,1.1,.1))
        pylab.yticks(pylab.arange(0,1.1,.1))
        pylab.grid(True)
        if equal_aspect:
            cax = pylab.gca()
            cax.set_aspect('equal')
        pylab.xlabel('1 - Specificity')
        pylab.ylabel('Sensitivity')
        pylab.title(title)

        pylab.show()
项目:seqhawkes    作者:mlukasik    | 项目源码 | 文件源码
def removeRightTicks(ax=None):
    ax = ax or pb.gca()
    for (i, line) in enumerate(ax.get_yticklines()):
        if i % 2 == 1:  # odd indices
            line.set_visible(False)
项目:seqhawkes    作者:mlukasik    | 项目源码 | 文件源码
def removeUpperTicks(ax=None):
    ax = ax or pb.gca()
    for (i, line) in enumerate(ax.get_xticklines()):
        if i % 2 == 1:  # odd indices
            line.set_visible(False)
项目:seqhawkes    作者:mlukasik    | 项目源码 | 文件源码
def fewerXticks(ax=None, divideby=2):
    ax = ax or pb.gca()
    ax.set_xticks(ax.get_xticks()[::divideby])
项目:astromalign    作者:dstndstn    | 项目源码 | 文件源码
def hsvoffsets(self, TT, rad, apply=False):
        print 'hsv offsets plot'
        plt.clf()

        for ix,X in enumerate(self.edges):
            X = self.get_edge_dradec_arcsec(ix, corrected=apply, goodonly=True)
            (matchRA, matchDec, dra, ddec) = X

            print 'matchRA,Dec:', len(matchRA), len(matchDec)
            print 'dra,dec:', len(dra), len(ddec)

            for ra,dec,dr,dd in zip(matchRA, matchDec, dra, ddec):
                angle = arctan2(dd, dr) / (2.*pi)
                angle = fmod(angle + 1, 1.)
                mag = hypot(dd, dr)
                mag = min(1, mag/(0.5*rad))
                rgb = colorsys.hsv_to_rgb(angle, mag, 0.5)
                plt.plot([ra], [dec], '.', color=rgb, alpha=0.5)

        # legend in top-right corner.
        ax=plt.axis()
        xlo,xhi = plt.gca().get_xlim()
        ylo,yhi = plt.gca().get_ylim()
        # fraction
        keycx = xlo + 0.90 * (xhi-xlo)
        keycy = ylo + 0.90 * (yhi-ylo)
        keyrx = 0.1 * (xhi-xlo) / 1.4 # HACK
        keyry = 0.1 * (yhi-ylo)
        nrings = 5
        for i,(rx,ry) in enumerate(zip(np.linspace(0, keyrx, nrings), np.linspace(0, keyry, nrings))):
            nspokes = ceil(i / float(nrings-1) * 30)
            angles = np.linspace(0, 2.*pi, nspokes, endpoint=False)
            for a in angles:
                rgb = colorsys.hsv_to_rgb(a/(2.*pi), float(i)/(nrings-1), 0.5)
                plt.plot([keycx + rx*sin(a)], [keycy + ry*cos(a)], '.', color=rgb, alpha=1.)
        plt.axis(ax)
        plt.xlabel('RA (deg)')
        plt.ylabel('Dec (deg)')
项目:facade-segmentation    作者:jfemiani    | 项目源码 | 文件源码
def plot(self):
        import pylab as pl
        ax = pl.gca()

        pl.hlines(self.tops, self.left, self.right, linestyles='dashed', colors='blue')
        pl.hlines(self.tops + self.heights, self.left, self.right, linestyles='dashed', colors='green')
        pl.vlines(self.lefts, self.top, self.bottom, linestyles='dashed', colors='blue')
        pl.vlines(self.lefts + self.widths, self.top, self.bottom, linestyles='dashed', colors='green')

        for box in self.rectangles:
            t, l, b, r = box
            patch = pl.Rectangle((l, t), r - l, b - t, color='blue', fill=True, alpha=0.5)
            ax.add_patch(patch)
        pass
项目:facade-segmentation    作者:jfemiani    | 项目源码 | 文件源码
def plot(self, bgimage=None):
        import pylab as pl

        self._plot_background(bgimage)
        ax = pl.gca()
        y0, y1 = pl.ylim()
        # r is the width of the thick line we use to show the facade colors
        r = 5
        patch = pl.Rectangle((self.facade_left + r, self.sky_line + r),
                             self.width - 2 * r,
                             self.door_line - self.sky_line - 2 * r,
                             color=self.color, fill=False, lw=2 * r)
        ax.add_patch(patch)

        pl.text((self.facade_right + self.facade_left) / 2.,
                (self.door_line + self.sky_line) / 2.,
                '$\sigma^2={:0.2f}$'.format(self.uncertainty_for_windows()))

        patch = pl.Rectangle((self.facade_left + r, self.door_line + r),
                             self.width - 2 * r,
                             y0 - self.door_line - 2 * r,
                             color=self.mezzanine_color, fill=False, lw=2 * r)
        ax.add_patch(patch)

        # Plot the left and right edges in yellow
        pl.vlines([self.facade_left, self.facade_right], self.sky_line, y0, colors='yellow')

        # Plot the door line and the roof line
        pl.hlines([self.door_line, self.sky_line], self.facade_left, self.facade_right, linestyles='dashed',
                  colors='yellow')

        self.window_grid.plot()
项目:facade-segmentation    作者:jfemiani    | 项目源码 | 文件源码
def plot_facade_cuts(self):

        facade_sig = self.facade_edge_scores.sum(0)
        facade_cuts = find_facade_cuts(facade_sig, dilation_amount=self.facade_merge_amount)
        mu = np.mean(facade_sig)
        sigma = np.std(facade_sig)

        w = self.rectified.shape[1]
        pad=10

        gs1 = pl.GridSpec(5, 5)
        gs1.update(wspace=0.5, hspace=0.0)  # set the spacing between axes.

        pl.subplot(gs1[:3, :])
        pl.imshow(self.rectified)
        pl.vlines(facade_cuts, *pl.ylim(), lw=2, color='black')
        pl.axis('off')
        pl.xlim(-pad, w+pad)

        pl.subplot(gs1[3:, :], sharex=pl.gca())
        pl.fill_between(np.arange(w), 0, facade_sig, lw=0, color='red')
        pl.fill_between(np.arange(w), 0, np.clip(facade_sig, 0, mu+sigma), color='blue')
        pl.plot(np.arange(w), facade_sig, color='blue')

        pl.vlines(facade_cuts, facade_sig[facade_cuts], pl.xlim()[1], lw=2, color='black')
        pl.scatter(facade_cuts, facade_sig[facade_cuts])

        pl.axis('off')

        pl.hlines(mu, 0, w, linestyle='dashed', color='black')
        pl.text(0, mu, '$\mu$ ', ha='right')

        pl.hlines(mu + sigma, 0, w, linestyle='dashed', color='gray',)
        pl.text(0, mu + sigma, '$\mu+\sigma$ ', ha='right')
        pl.xlim(-pad, w+pad)
项目:svm-street-detector    作者:morris-frank    | 项目源码 | 文件源码
def saveBEVImageWithAxes(data, outputname, cmap = None, xlabel = 'x [m]', ylabel = 'z [m]', rangeX = [-10, 10], rangeXpx = None, numDeltaX = 5, rangeZ = [7, 62], rangeZpx = None, numDeltaZ = 5, fontSize = 16):
    '''

    :param data:
    :param outputname:
    :param cmap:
    '''
    aspect_ratio = float(data.shape[1])/data.shape[0]
    fig = pylab.figure()
    Scale = 8
    # add +1 to get axis text
    fig.set_size_inches(Scale*aspect_ratio+1,Scale*1)
    ax = pylab.gca()
    #ax.set_axis_off()
    #fig.add_axes(ax)
    if cmap != None:
        pylab.set_cmap(cmap)

    #ax.imshow(data, interpolation='nearest', aspect = 'normal')
    ax.imshow(data, interpolation='nearest')

    if rangeXpx == None:
        rangeXpx = (0, data.shape[1])

    if rangeZpx == None:
        rangeZpx = (0, data.shape[0])

    modBev_plot(ax, rangeX, rangeXpx, numDeltaX, rangeZ, rangeZpx, numDeltaZ, fontSize, xlabel = xlabel, ylabel = ylabel)
    #plt.savefig(outputname, bbox_inches='tight', dpi = dpi)
    pylab.savefig(outputname, dpi = data.shape[0]/Scale)
    pylab.close()
    fig.clear()
项目:VOCSeg    作者:lxh-123    | 项目源码 | 文件源码
def saveBEVImageWithAxes(data, outputname, cmap = None, xlabel = 'x [m]', ylabel = 'z [m]', rangeX = [-10, 10], rangeXpx = None, numDeltaX = 5, rangeZ = [7, 62], rangeZpx = None, numDeltaZ = 5, fontSize = 16):
    '''

    :param data:
    :param outputname:
    :param cmap:
    '''
    aspect_ratio = float(data.shape[1])/data.shape[0]
    fig = pylab.figure()
    Scale = 8
    # add +1 to get axis text
    fig.set_size_inches(Scale*aspect_ratio+1,Scale*1)
    ax = pylab.gca()
    #ax.set_axis_off()
    #fig.add_axes(ax)
    if cmap != None:
        pylab.set_cmap(cmap)

    #ax.imshow(data, interpolation='nearest', aspect = 'normal')
    ax.imshow(data, interpolation='nearest')

    if rangeXpx == None:
        rangeXpx = (0, data.shape[1])

    if rangeZpx == None:
        rangeZpx = (0, data.shape[0])

    modBev_plot(ax, rangeX, rangeXpx, numDeltaX, rangeZ, rangeZpx, numDeltaZ, fontSize, xlabel = xlabel, ylabel = ylabel)
    #plt.savefig(outputname, bbox_inches='tight', dpi = dpi)
    pylab.savefig(outputname, dpi = data.shape[0]/Scale)
    pylab.close()
    fig.clear()
项目:VOCSeg    作者:lxh-123    | 项目源码 | 文件源码
def saveBEVImageWithAxes(data, outputname, cmap = None, xlabel = 'x [m]', ylabel = 'z [m]', rangeX = [-10, 10], rangeXpx = None, numDeltaX = 5, rangeZ = [7, 62], rangeZpx = None, numDeltaZ = 5, fontSize = 16):
    '''

    :param data:
    :param outputname:
    :param cmap:
    '''
    aspect_ratio = float(data.shape[1])/data.shape[0]
    fig = pylab.figure()
    Scale = 8
    # add +1 to get axis text
    fig.set_size_inches(Scale*aspect_ratio+1,Scale*1)
    ax = pylab.gca()
    #ax.set_axis_off()
    #fig.add_axes(ax)
    if cmap != None:
        pylab.set_cmap(cmap)

    #ax.imshow(data, interpolation='nearest', aspect = 'normal')
    ax.imshow(data, interpolation='nearest')

    if rangeXpx == None:
        rangeXpx = (0, data.shape[1])

    if rangeZpx == None:
        rangeZpx = (0, data.shape[0])

    modBev_plot(ax, rangeX, rangeXpx, numDeltaX, rangeZ, rangeZpx, numDeltaZ, fontSize, xlabel = xlabel, ylabel = ylabel)
    #plt.savefig(outputname, bbox_inches='tight', dpi = dpi)
    pylab.savefig(outputname, dpi = data.shape[0]/Scale)
    pylab.close()
    fig.clear()
项目:KittiSeg    作者:MarvinTeichmann    | 项目源码 | 文件源码
def saveBEVImageWithAxes(data, outputname, cmap = None, xlabel = 'x [m]', ylabel = 'z [m]', rangeX = [-10, 10], rangeXpx = None, numDeltaX = 5, rangeZ = [7, 62], rangeZpx = None, numDeltaZ = 5, fontSize = 16):
    '''

    :param data:
    :param outputname:
    :param cmap:
    '''
    aspect_ratio = float(data.shape[1])/data.shape[0]
    fig = pylab.figure()
    Scale = 8
    # add +1 to get axis text
    fig.set_size_inches(Scale*aspect_ratio+1,Scale*1)
    ax = pylab.gca()
    #ax.set_axis_off()
    #fig.add_axes(ax)
    if cmap != None:
        pylab.set_cmap(cmap)

    #ax.imshow(data, interpolation='nearest', aspect = 'normal')
    ax.imshow(data, interpolation='nearest')

    if rangeXpx == None:
        rangeXpx = (0, data.shape[1])

    if rangeZpx == None:
        rangeZpx = (0, data.shape[0])

    modBev_plot(ax, rangeX, rangeXpx, numDeltaX, rangeZ, rangeZpx, numDeltaZ, fontSize, xlabel = xlabel, ylabel = ylabel)
    #plt.savefig(outputname, bbox_inches='tight', dpi = dpi)
    pylab.savefig(outputname, dpi = data.shape[0]/Scale)
    pylab.close()
    fig.clear()
项目:KittiSeg    作者:MarvinTeichmann    | 项目源码 | 文件源码
def saveBEVImageWithAxes(data, outputname, cmap = None, xlabel = 'x [m]', ylabel = 'z [m]', rangeX = [-10, 10], rangeXpx = None, numDeltaX = 5, rangeZ = [7, 62], rangeZpx = None, numDeltaZ = 5, fontSize = 16):
    '''

    :param data:
    :param outputname:
    :param cmap:
    '''
    aspect_ratio = float(data.shape[1])/data.shape[0]
    fig = pylab.figure()
    Scale = 8
    # add +1 to get axis text
    fig.set_size_inches(Scale*aspect_ratio+1,Scale*1)
    ax = pylab.gca()
    #ax.set_axis_off()
    #fig.add_axes(ax)
    if cmap != None:
        pylab.set_cmap(cmap)

    #ax.imshow(data, interpolation='nearest', aspect = 'normal')
    ax.imshow(data, interpolation='nearest')

    if rangeXpx == None:
        rangeXpx = (0, data.shape[1])

    if rangeZpx == None:
        rangeZpx = (0, data.shape[0])

    modBev_plot(ax, rangeX, rangeXpx, numDeltaX, rangeZ, rangeZpx, numDeltaZ, fontSize, xlabel = xlabel, ylabel = ylabel)
    #plt.savefig(outputname, bbox_inches='tight', dpi = dpi)
    pylab.savefig(outputname, dpi = data.shape[0]/Scale)
    pylab.close()
    fig.clear()
项目:KittiSeg    作者:MarvinTeichmann    | 项目源码 | 文件源码
def saveBEVImageWithAxes(data, outputname, cmap = None, xlabel = 'x [m]', ylabel = 'z [m]', rangeX = [-10, 10], rangeXpx = None, numDeltaX = 5, rangeZ = [7, 62], rangeZpx = None, numDeltaZ = 5, fontSize = 16):
    '''

    :param data:
    :param outputname:
    :param cmap:
    '''
    aspect_ratio = float(data.shape[1])/data.shape[0]
    fig = pylab.figure()
    Scale = 8
    # add +1 to get axis text
    fig.set_size_inches(Scale*aspect_ratio+1,Scale*1)
    ax = pylab.gca()
    #ax.set_axis_off()
    #fig.add_axes(ax)
    if cmap != None:
        pylab.set_cmap(cmap)

    #ax.imshow(data, interpolation='nearest', aspect = 'normal')
    ax.imshow(data, interpolation='nearest')

    if rangeXpx == None:
        rangeXpx = (0, data.shape[1])

    if rangeZpx == None:
        rangeZpx = (0, data.shape[0])

    modBev_plot(ax, rangeX, rangeXpx, numDeltaX, rangeZ, rangeZpx, numDeltaZ, fontSize, xlabel = xlabel, ylabel = ylabel)
    #plt.savefig(outputname, bbox_inches='tight', dpi = dpi)
    pylab.savefig(outputname, dpi = data.shape[0]/Scale)
    pylab.close()
    fig.clear()
项目:tap    作者:mfouesneau    | 项目源码 | 文件源码
def theme(ax=None, minorticks=False):
    """ update plot to make it nice and uniform """
    from matplotlib.ticker import AutoMinorLocator
    from pylab import rcParams, gca, tick_params
    if minorticks:
        if ax is None:
            ax = gca()
        ax.yaxis.set_minor_locator(AutoMinorLocator())
        ax.xaxis.set_minor_locator(AutoMinorLocator())
    tick_params(which='both', width=rcParams['lines.linewidth'])
项目:tap    作者:mfouesneau    | 项目源码 | 文件源码
def histplot(data, bins=10, range=None, normed=False, weights=None, density=None, ax=None, **kwargs):
    """ plot an histogram of data `a la R`: only bottom and left axis, with
    dots at the bottom to represent the sample

    Example
    -------
        import numpy as np
        x = np.random.normal(0, 1, 1e3)
        histplot(x, bins=50, density=True, ls='steps-mid')
    """
    h, b = np.histogram(data, bins, range, normed, weights, density)
    if ax is None:
        ax = plt.gca()
    x = 0.5 * (b[:-1] + b[1:])
    l = ax.plot(x, h, **kwargs)

    ax.xaxis.set_ticks_position('bottom')
    ax.yaxis.set_ticks_position('left')

    _w = ['top', 'right']
    [ ax.spines[side].set_visible(False) for side in _w ]

    for wk in ['bottom', 'left']:
        ax.spines[wk].set_position(('outward', 10))

    ylim = ax.get_ylim()
    ax.plot(data, -0.02 * max(ylim) * np.ones(len(data)), '|', color=l[0].get_color())
    ax.set_ylim(-0.02 * max(ylim), max(ylim))
项目:tap    作者:mfouesneau    | 项目源码 | 文件源码
def imshow(self, **kwargs):
        defaults = {'origin': 'lower', 'cmap': plt.cm.Greys,
                    'interpolation':'nearest', 'aspect':'auto'}
        defaults.update(**kwargs)
        ax = kwargs.pop('ax', plt.gca())
        return ax.imshow(self.im.T, extent=self.e, **defaults)
项目:tap    作者:mfouesneau    | 项目源码 | 文件源码
def contour(self, *args, **kwargs):
        defaults = {'origin': 'lower', 'cmap': plt.cm.Greys,
                    'levels': np.sort(self.nice_levels())}
        defaults.update(**kwargs)
        ax = kwargs.pop('ax', plt.gca())
        return ax.contour(self.im.T, *args, extent=self.e, **defaults)
项目:tap    作者:mfouesneau    | 项目源码 | 文件源码
def contourf(self, *args, **kwargs):
        defaults = {'origin': 'lower', 'cmap': plt.cm.Greys,
                    'levels': self.nice_levels()}
        defaults.update(**kwargs)
        ax = kwargs.pop('ax', plt.gca())
        return ax.contourf(self.im.T, *args,  extent=self.e, **defaults)
项目:tap    作者:mfouesneau    | 项目源码 | 文件源码
def plot(self, ax=None, orientation='horizontal', cutoff=False, log=False,
             cutoff_type='std', cutoff_val=1.5, pos=100, pos_marker='line',
             pos_width=0.05, pos_kwargs={}, **kwargs):

        if ax is None:
            ax = plt.gca()

        # Draw the violin.
        if ('facecolor' not in kwargs) | ('fc' not in kwargs):
            kwargs['facecolor'] = 'y'
        if ('edgecolor' not in kwargs) | ('ec' not in kwargs):
            kwargs['edgecolor'] = 'k'
        if ('alpha' not in kwargs.keys()):
            kwargs['alpha'] = 0.5

        if 'color' in kwargs:
            kwargs['edgecolor'] = kwargs['color']
            kwargs['facecolor'] = kwargs['color']

        # Kernel density estimate for data at this position.
        violin, e = self.im, self.e
        xvals = np.linspace(e[0], e[1], len(violin))

        xvals = np.hstack(([xvals[0]], xvals, [xvals[-1]]))
        violin = np.hstack(([0], violin, [0]))

        if orientation == 'horizontal':
            ax.fill(xvals, violin, **kwargs)
        elif orientation == 'vertical':
            ax.fill_betweenx(xvals, 0, violin, **kwargs)

        plt.draw_if_interactive()
项目:ugali    作者:DarkEnergySurvey    | 项目源码 | 文件源码
def cmPlot(targ_ra, targ_dec, data, iso, g_radius, nbhd, type):
    """Color-magnitude plot"""

    angsep = ugali.utils.projector.angsep(targ_ra, targ_dec, data['RA'], data['DEC'])
    annulus = (angsep > g_radius) & (angsep < 1.)

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

    if type == 'stars':
        filter = star_filter(data)
        plt.title('Stellar Color-Magnitude')
    elif type == 'galaxies':
        filter = galaxy_filter(data)
        plt.title('Galactic Color-Magnitude')

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

    # Plot background objects
    plt.scatter(mag_g[filter & annulus] - mag_r[filter & annulus], mag_g[filter & annulus], c='k', alpha=0.1, edgecolor='none', s=1)

    # Plot isochrone
    ugali.utils.plotting.drawIsochrone(iso, lw=2, label='{} Gyr, z = {}'.format(iso.age, iso.metallicity))

    # Plot objects in nbhd
    plt.scatter(mag_g[filter & nbhd] - mag_r[filter & nbhd], mag_g[filter & nbhd], c='g', s=5, label='r < {:.3f}$^\circ$'.format(g_radius))

    # Plot objects in nbhd and near isochrone
    plt.scatter(mag_g[filter & nbhd & iso_filter] - mag_r[filter & nbhd & iso_filter], mag_g[filter & nbhd & iso_filter], c='r', s=5, label='$\Delta$CM < 0.1')

    plt.axis([-0.5, 1, 16, 24])
    plt.gca().invert_yaxis()
    plt.gca().set_aspect(1./4.)
    plt.legend(loc='upper left')
    plt.xlabel('g-r (mag)')
    plt.ylabel('g (mag)')
项目:ugali    作者:DarkEnergySurvey    | 项目源码 | 文件源码
def drawHealpixMap(map, lon, lat, size=1.0, xsize=501, coord='GC', **kwargs):
    """
    Draw local projection of healpix map.
    """
    ax = plt.gca()
    x = np.linspace(-size,size,xsize)
    y = np.linspace(-size,size,xsize)
    xx, yy = np.meshgrid(x,y)

    coord = coord.upper()

    if coord == 'GC':
        #Assumes map and (lon,lat) are Galactic, but plotting celestial
        llon, llat = image2sphere(*gal2cel(lon,lat),x=xx.flat,y=yy.flat)
        pix = ang2pix(healpy.get_nside(map),*cel2gal(llon,llat))
    elif coord == 'CG':
        #Assumes map and (lon,lat) are celestial, but plotting Galactic
        llon, llat = image2sphere(*cel2gal(lon,lat),x=xx.flat,y=yy.flat)
        pix = ang2pix(healpy.get_nside(map),*gal2cel(llon,llat))
    else:
        #Assumes plotting the native coordinates
        llon, llat = image2sphere(lon,lat,xx.flat,yy.flat)
        pix = ang2pix(healpy.get_nside(map),llon,llat)

    values = map[pix].reshape(xx.shape)
    zz = np.ma.array(values,mask=(values==healpy.UNSEEN),fill_value=np.nan)

    return drawProjImage(xx,yy,zz,coord=coord,**kwargs)
项目:ugali    作者:DarkEnergySurvey    | 项目源码 | 文件源码
def drawImage(self,ax=None,invert=True):
        if not ax: ax = plt.gca()

        if self.config['data']['survey']=='sdss':
            # Optical Image
            im = ugali.utils.plotting.getSDSSImage(**self.image_kwargs)
            # Flipping JPEG:
            # https://github.com/matplotlib/matplotlib/issues/101
            im = im[::-1]
            ax.annotate("SDSS Image",**self.label_kwargs)
        else: 
            im = ugali.utils.plotting.getDSSImage(**self.image_kwargs)
            im = im[::-1,::-1]
            ax.annotate("DSS Image",**self.label_kwargs)

        size=self.image_kwargs.get('radius',1.0)

        # Celestial coordinates
        x = np.linspace(-size,size,im.shape[0])
        y = np.linspace(-size,size,im.shape[1])
        xx, yy = np.meshgrid(x,y)

        #kwargs = dict(cmap='gray',interpolation='none')
        kwargs = dict(cmap='gray',coord='C')
        im = drawProjImage(xx,yy,im,**kwargs)

        try: plt.gcf().delaxes(ax.cax)
        except AttributeError: pass

        return im
项目:ugali    作者:DarkEnergySurvey    | 项目源码 | 文件源码
def drawCatalog(self, ax=None):
        if not ax: ax = plt.gca()
        # Stellar Catalog
        self._create_catalog()
        healpy.projscatter(self.catalog.lon,self.catalog.lat,c='k',marker='.',lonlat=True,coord=self.gnom_kwargs['coord'])
        ax.annotate("Stars",**self.label_kwargs)
项目:ugali    作者:DarkEnergySurvey    | 项目源码 | 文件源码
def drawSpatial(self, ax=None):
        if not ax: ax = plt.gca()
        # Stellar Catalog
        self._create_catalog()
        cut = (self.catalog.color > 0) & (self.catalog.color < 1)
        catalog = self.catalog.applyCut(cut)
        ax.scatter(catalog.lon,catalog.lat,c='k',marker='.',s=1)
        ax.set_xlim(self.glon-0.5,self.glon+0.5)
        ax.set_ylim(self.glat-0.5,self.glat+0.5)
        ax.set_xlabel('GLON (deg)')
        ax.set_ylabel('GLAT (deg)')
项目: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 drawTS(self, filename=None, zidx=None):
        ax = plt.gca()
        if zidx is None: zidx = self.zidx
        super(ObjectPlotter,self).drawTS(ax,filename,zidx)
项目:ugali    作者:DarkEnergySurvey    | 项目源码 | 文件源码
def drawMembership(self, radius=None, zidx=None, mc_source_id=1):
        ax = plt.gca()
        if zidx is None: zidx = self.zidx
        super(ObjectPlotter,self).drawMembership(ax,radius,zidx,mc_source_id)
项目:ugali    作者:DarkEnergySurvey    | 项目源码 | 文件源码
def drawHessDiagram(self,catalog=None):
        ax = plt.gca()
        if not catalog: catalog = self.get_stars()

        r_peak = self.kernel.extension
        angsep = ugali.utils.projector.angsep(self.ra, self.dec, catalog.ra, catalog.dec)
        cut_inner = (angsep < r_peak)
        cut_annulus = (angsep > 0.5) & (angsep < 1.) # deg

        mmin, mmax = 16., 24.
        cmin, cmax = -0.5, 1.0
        mbins = np.linspace(mmin, mmax, 150)
        cbins = np.linspace(cmin, cmax, 150)

        color = catalog.color[cut_annulus]
        mag = catalog.mag[cut_annulus]

        h, xbins, ybins = numpy.histogram2d(color, mag, bins=[cbins,mbins])
        blur = nd.filters.gaussian_filter(h.T, 2)
        kwargs = dict(extent=[xbins.min(),xbins.max(),ybins.min(),ybins.max()],
                      cmap='gray_r', aspect='auto', origin='lower', 
                      rasterized=True, interpolation='none')
        ax.imshow(blur, **kwargs)

        pylab.scatter(catalog.color[cut_inner], catalog.mag[cut_inner], 
                      c='red', s=7, edgecolor='none')# label=r'$r < %.2f$ deg'%(r_peak))
        ugali.utils.plotting.drawIsochrone(self.isochrone, c='b', zorder=10)
        ax.set_xlim(-0.5, 1.)
        ax.set_ylim(24., 16.)
        plt.xlabel(r'$g - r$')
        plt.ylabel(r'$g$')
        plt.xticks([-0.5, 0., 0.5, 1.])
        plt.yticks(numpy.arange(mmax - 1., mmin - 1., -1.))

        radius_string = (r'${\rm r}<%.1f$ arcmin'%( 60 * r_peak))
        pylab.text(0.05, 0.95, radius_string, 
                   fontsize=10, ha='left', va='top', color='red', 
                   transform=pylab.gca().transAxes,
                   bbox=dict(facecolor='white', alpha=1., edgecolor='none'))
项目: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()
项目:PyPeVoc    作者:goiosunsw    | 项目源码 | 文件源码
def plot_time_freq(self, minlen=10):
        part = [pp for pp in self.partial if len(pp.f) > minlen]
        pl.figure()
        pl.hold(True)
        for pp in part:
            pl.plot(pp.start_idx + np.arange(len(pp.f)), np.array(pp.f))
        pl.hold(False)
        pl.xlabel('Time (s)')
        pl.ylabel('Frequency (Hz)')
        # pl.show()
        return pl.gca()
项目:SkinLesionNeuralNetwork    作者:Neurality    | 项目源码 | 文件源码
def save_weights_png(model):
    print "HEY!"
    for layer in model.layers:
        weights = layer.get_weights()
        print layer.name
    pl.figure(figsize=(5, 5))
    pl.title('conv1 weights')
    nice_imshow(pl.gca(), make_mosaic(printable, 6, 6), cmap=cm.binary)