Python matplotlib.colors 模块,BoundaryNorm() 实例源码

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

项目:ai_examples    作者:jaara    | 项目源码 | 文件源码
def displayBrain(brain, res=25):    
    mapV, mapA = mapBrain(brain, res)

    plt.close()
    plt.show()  

    fig = plt.figure(figsize=(5,7))
    fig.add_subplot(211)

    plt.imshow(mapV)
    plt.colorbar(orientation='vertical')

    fig.add_subplot(212)

    cmap = colors.ListedColormap(['yellow', 'blue', 'white', 'red'])
    bounds=[-1.5,-0.5,0.5,1.5,2.5]
    norm = colors.BoundaryNorm(bounds, cmap.N)

    plt.imshow(mapA, cmap=cmap, norm=norm)        
    cb = plt.colorbar(orientation='vertical', ticks=[-1,0,1,2])

    plt.pause(0.001)
项目:snake_game    作者:wing3s    | 项目源码 | 文件源码
def save_image(folder='images'):
    """
    Coroutine of image saving
    """
    from matplotlib import pyplot as plt
    from matplotlib import colors

    if folder not in os.listdir('.'):
        os.mkdir(folder)
    frame_cnt = it.count()

    cmap = colors.ListedColormap(['#009688', '#E0F2F1', '#004D40'])
    bounds = [0, 0.25, 0.75, 1]
    norm = colors.BoundaryNorm(bounds, cmap.N)

    while True:
        screen = (yield)
        shape = screen.shape
        plt.imshow(
            screen,
            interpolation='none',
            cmap=cmap,
            norm=norm,
            aspect='equal',
            extent=(0, shape[1], 0, shape[0]))
        plt.grid(True)
        plt.axis('off')
        plt.savefig('%s/frame%06i.png' % (folder, frame_cnt.next()))
项目:prince    作者:MaxHalford    | 项目源码 | 文件源码
def add_color_bar(ax, cmap, labels):
    """Add a colorbar to an axis.

    Args:
        ax (AxesSubplot)
        cmap (Colormap): A prepaped colormap of size n.
        labels (list of str): A list of strings of size n.
    """
    norm = clr.BoundaryNorm(list(range(cmap.N+1)), cmap.N)
    smap = cm.ScalarMappable(norm=norm, cmap=cmap)
    smap.set_array([])
    cbar = plt.colorbar(smap, ax=ax)
    cbar.set_ticks([i + 0.5 for i in range(cmap.N)])
    cbar.set_ticklabels(labels)
项目:Pytorch-Deeplab    作者:speedinghzl    | 项目源码 | 文件源码
def show_all(gt, pred):
    import matplotlib.pyplot as plt
    from matplotlib import colors
    from mpl_toolkits.axes_grid1 import make_axes_locatable

    fig, axes = plt.subplots(1, 2)
    ax1, ax2 = axes

    classes = np.array(('background',  # always index 0
               'aeroplane', 'bicycle', 'bird', 'boat',
               'bottle', 'bus', 'car', 'cat', 'chair',
                         'cow', 'diningtable', 'dog', 'horse',
                         'motorbike', 'person', 'pottedplant',
                         'sheep', 'sofa', 'train', 'tvmonitor'))
    colormap = [(0,0,0),(0.5,0,0),(0,0.5,0),(0.5,0.5,0),(0,0,0.5),(0.5,0,0.5),(0,0.5,0.5), 
                    (0.5,0.5,0.5),(0.25,0,0),(0.75,0,0),(0.25,0.5,0),(0.75,0.5,0),(0.25,0,0.5), 
                    (0.75,0,0.5),(0.25,0.5,0.5),(0.75,0.5,0.5),(0,0.25,0),(0.5,0.25,0),(0,0.75,0), 
                    (0.5,0.75,0),(0,0.25,0.5)]
    cmap = colors.ListedColormap(colormap)
    bounds=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21]
    norm = colors.BoundaryNorm(bounds, cmap.N)

    ax1.set_title('gt')
    ax1.imshow(gt, cmap=cmap, norm=norm)

    ax2.set_title('pred')
    ax2.imshow(pred, cmap=cmap, norm=norm)

    plt.show()
项目:Pytorch-Deeplab    作者:speedinghzl    | 项目源码 | 文件源码
def show_all(gt, pred):
    import matplotlib.pyplot as plt
    from matplotlib import colors
    from mpl_toolkits.axes_grid1 import make_axes_locatable

    fig, axes = plt.subplots(1, 2)
    ax1, ax2 = axes

    classes = np.array(('background',  # always index 0
               'aeroplane', 'bicycle', 'bird', 'boat',
               'bottle', 'bus', 'car', 'cat', 'chair',
                         'cow', 'diningtable', 'dog', 'horse',
                         'motorbike', 'person', 'pottedplant',
                         'sheep', 'sofa', 'train', 'tvmonitor'))
    colormap = [(0,0,0),(0.5,0,0),(0,0.5,0),(0.5,0.5,0),(0,0,0.5),(0.5,0,0.5),(0,0.5,0.5), 
                    (0.5,0.5,0.5),(0.25,0,0),(0.75,0,0),(0.25,0.5,0),(0.75,0.5,0),(0.25,0,0.5), 
                    (0.75,0,0.5),(0.25,0.5,0.5),(0.75,0.5,0.5),(0,0.25,0),(0.5,0.25,0),(0,0.75,0), 
                    (0.5,0.75,0),(0,0.25,0.5)]
    cmap = colors.ListedColormap(colormap)
    bounds=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21]
    norm = colors.BoundaryNorm(bounds, cmap.N)

    ax1.set_title('gt')
    ax1.imshow(gt, cmap=cmap, norm=norm)

    ax2.set_title('pred')
    ax2.imshow(pred, cmap=cmap, norm=norm)

    plt.show()
项目:PaleoView    作者:GlobalEcologyLab    | 项目源码 | 文件源码
def _proportional_y(self):
        '''
        Return colorbar data coordinates for the boundaries of
        a proportional colorbar.
        '''
        if isinstance(self.norm, colors.BoundaryNorm):
            y = (self._boundaries - self._boundaries[0])
            y = y / (self._boundaries[-1] - self._boundaries[0])
        else:
            y = self.norm(self._boundaries.copy())
        if self.extend == 'min':
            # Exclude leftmost interval of y.
            clen = y[-1] - y[1]
            automin = (y[2] - y[1]) / clen
            automax = (y[-1] - y[-2]) / clen
        elif self.extend == 'max':
            # Exclude rightmost interval in y.
            clen = y[-2] - y[0]
            automin = (y[1] - y[0]) / clen
            automax = (y[-2] - y[-3]) / clen
        else:
            # Exclude leftmost and rightmost intervals in y.
            clen = y[-2] - y[1]
            automin = (y[2] - y[1]) / clen
            automax = (y[-2] - y[-3]) / clen
        extendlength = self._get_extension_lengths(self.extendfrac,
                                                   automin, automax,
                                                   default=0.05)
        if self.extend in ('both', 'min'):
            y[0] = 0. - extendlength[0]
        if self.extend in ('both', 'max'):
            y[-1] = 1. + extendlength[1]
        yi = y[self._inside]
        norm = colors.Normalize(yi[0], yi[-1])
        y[self._inside] = norm(yi)
        return y
项目:PaleoView    作者:GlobalEcologyLab    | 项目源码 | 文件源码
def _locate(self, x):
        '''
        Given a set of color data values, return their
        corresponding colorbar data coordinates.
        '''
        if isinstance(self.norm, (colors.NoNorm, colors.BoundaryNorm)):
            b = self._boundaries
            xn = x
        else:
            # Do calculations using normalized coordinates so
            # as to make the interpolation more accurate.
            b = self.norm(self._boundaries, clip=False).filled()
            xn = self.norm(x, clip=False).filled()
        # The rest is linear interpolation with extrapolation at ends.
        y = self._y
        N = len(b)
        ii = np.searchsorted(b, xn)
        i0 = ii - 1
        itop = (ii == N)
        ibot = (ii == 0)
        i0[itop] -= 1
        ii[itop] -= 1
        i0[ibot] += 1
        ii[ibot] += 1

        #db = b[ii] - b[i0]
        db = np.take(b, ii) - np.take(b, i0)
        #dy = y[ii] - y[i0]
        dy = np.take(y, ii) - np.take(y, i0)
        z = np.take(y, i0) + (xn - np.take(b, i0)) * dy / db

        return z
项目:PaleoView    作者:GlobalEcologyLab    | 项目源码 | 文件源码
def _proportional_y(self):
        '''
        Return colorbar data coordinates for the boundaries of
        a proportional colorbar.
        '''
        if isinstance(self.norm, colors.BoundaryNorm):
            y = (self._boundaries - self._boundaries[0])
            y = y / (self._boundaries[-1] - self._boundaries[0])
        else:
            y = self.norm(self._boundaries.copy())
        if self.extend == 'min':
            # Exclude leftmost interval of y.
            clen = y[-1] - y[1]
            automin = (y[2] - y[1]) / clen
            automax = (y[-1] - y[-2]) / clen
        elif self.extend == 'max':
            # Exclude rightmost interval in y.
            clen = y[-2] - y[0]
            automin = (y[1] - y[0]) / clen
            automax = (y[-2] - y[-3]) / clen
        else:
            # Exclude leftmost and rightmost intervals in y.
            clen = y[-2] - y[1]
            automin = (y[2] - y[1]) / clen
            automax = (y[-2] - y[-3]) / clen
        extendlength = self._get_extension_lengths(self.extendfrac,
                                                   automin, automax,
                                                   default=0.05)
        if self.extend in ('both', 'min'):
            y[0] = 0. - extendlength[0]
        if self.extend in ('both', 'max'):
            y[-1] = 1. + extendlength[1]
        yi = y[self._inside]
        norm = colors.Normalize(yi[0], yi[-1])
        y[self._inside] = norm(yi)
        return y
项目:pymake    作者:dtrckd    | 项目源码 | 文件源码
def adjblocks(Y, clusters=None, title=''):
    """ Make a colormap image of a matrix
        :key Y: the matrix to be used for the colormap.
    """
    # Artefact
    #np.fill_diagonal(Y, 0)

    plt.figure()
    if clusters is None:
        plt.axis('off')
        cmap = 'Greys'
        norm = None
        y = Y
    else:
        plt.axis('on')
        y = reorder_mat(Y, clusters, reverse=True)
        hist, label = clusters_hist(clusters)
        # Colors Setup
        u_colors.reset()
        #cmap = Colors.ListedColormap(['white','black']+ u_colors.seq[:len(hist)**2])
        cmap = Colors.ListedColormap(['#000000', '#FFFFFF']+ u_colors.seq[:len(hist)**2])
        bounds = np.arange(len(hist)**2+2)
        norm = Colors.BoundaryNorm(bounds, cmap.N)
        # Iterate over blockmodel
        for k, count_k in enumerate(hist):
            for l, count_l in enumerate(hist):
                # Draw a colored square (not white and black)
                topleft =  (hist[:k].sum(), hist[:l].sum())
                w = int(0.01 * y.shape[0])
                # write on place
                draw_square(y, k+l+2, topleft, count_k, count_l, w)

    implt = plt.imshow(y, cmap=cmap, norm=norm,
                       clim=(np.amin(y), np.amax(y)),
                       interpolation='nearest',)
                       #origin='upper') # change shape !
    #plt.colorbar()
    plt.title(title)
    #plt.savefig(filename, fig=fig, facecolor='white', edgecolor='black')
项目:percolation    作者:bluepatoune    | 项目源码 | 文件源码
def percolation(matrice):  # methode 2
    """Dessine la propagation de l'eau, et indique s'il y a percolation."""
    cmap = colors.ListedColormap(couleurs) # TODO: Relève du display, à metttre ailleurs.
    norm = colors.BoundaryNorm(valeurs + [max(valeurs)+1], cmap.N)
    pyplot.matshow([valeurs], 1, cmap=cmap, norm=norm)
    pyplot.pause(1)

    eau_mouvante = initialisation_eau_mouvante(matrice)
    while eau_mouvante != []:

        pyplot.matshow(matrice, 1, cmap=cmap, norm=norm) # TODO: Séparer la logique de display de la logique de génération (threads ?)
        pyplot.pause(.0001)

        eau_mouvante = propagation(matrice,eau_mouvante)
    return resultat(matrice)
项目:PaleoView    作者:GlobalEcologyLab    | 项目源码 | 文件源码
def _ticker(self):
        '''
        Return two sequences: ticks (colorbar data locations)
        and ticklabels (strings).
        '''
        locator = self.locator
        formatter = self.formatter
        if locator is None:
            if self.boundaries is None:
                if isinstance(self.norm, colors.NoNorm):
                    nv = len(self._values)
                    base = 1 + int(nv / 10)
                    locator = ticker.IndexLocator(base=base, offset=0)
                elif isinstance(self.norm, colors.BoundaryNorm):
                    b = self.norm.boundaries
                    locator = ticker.FixedLocator(b, nbins=10)
                elif isinstance(self.norm, colors.LogNorm):
                    locator = ticker.LogLocator()
                else:
                    locator = ticker.MaxNLocator()
            else:
                b = self._boundaries[self._inside]
                locator = ticker.FixedLocator(b, nbins=10)
        if isinstance(self.norm, colors.NoNorm):
            intv = self._values[0], self._values[-1]
        else:
            intv = self.vmin, self.vmax
        locator.create_dummy_axis(minpos=intv[0])
        formatter.create_dummy_axis(minpos=intv[0])
        locator.set_view_interval(*intv)
        locator.set_data_interval(*intv)
        formatter.set_view_interval(*intv)
        formatter.set_data_interval(*intv)

        b = np.array(locator())
        ticks = self._locate(b)
        inrange = (ticks > -0.001) & (ticks < 1.001)
        ticks = ticks[inrange]
        b = b[inrange]
        formatter.set_locs(b)
        ticklabels = [formatter(t, i) for i, t in enumerate(b)]
        offset_string = formatter.get_offset()
        return ticks, ticklabels, offset_string
项目:PaleoView    作者:GlobalEcologyLab    | 项目源码 | 文件源码
def _ticker(self):
        '''
        Return the sequence of ticks (colorbar data locations),
        ticklabels (strings), and the corresponding offset string.
        '''
        locator = self.locator
        formatter = self.formatter
        if locator is None:
            if self.boundaries is None:
                if isinstance(self.norm, colors.NoNorm):
                    nv = len(self._values)
                    base = 1 + int(nv / 10)
                    locator = ticker.IndexLocator(base=base, offset=0)
                elif isinstance(self.norm, colors.BoundaryNorm):
                    b = self.norm.boundaries
                    locator = ticker.FixedLocator(b, nbins=10)
                elif isinstance(self.norm, colors.LogNorm):
                    locator = ticker.LogLocator()
                else:
                    locator = ticker.MaxNLocator()
            else:
                b = self._boundaries[self._inside]
                locator = ticker.FixedLocator(b, nbins=10)
        if isinstance(self.norm, colors.NoNorm):
            intv = self._values[0], self._values[-1]
        else:
            intv = self.vmin, self.vmax
        locator.create_dummy_axis(minpos=intv[0])
        formatter.create_dummy_axis(minpos=intv[0])
        locator.set_view_interval(*intv)
        locator.set_data_interval(*intv)
        formatter.set_view_interval(*intv)
        formatter.set_data_interval(*intv)

        b = np.array(locator())
        ticks = self._locate(b)
        inrange = (ticks > -0.001) & (ticks < 1.001)
        ticks = ticks[inrange]
        b = b[inrange]
        formatter.set_locs(b)
        ticklabels = [formatter(t, i) for i, t in enumerate(b)]
        offset_string = formatter.get_offset()
        return ticks, ticklabels, offset_string
项目:RapidMoc    作者:cdr30    | 项目源码 | 文件源码
def plot_streamfunction_hovmollers(trans, name='simulated', basename='', obs=None):
    """ Plot overturning stream function hovmoller diagrams"""

    # Extract variables from data objects
    dts = utils.get_ncdates(trans)
    z = trans.variables['depth'][:]
    sf_rapid = trans.variables['sf_rapid'][:]
    sf_model = trans.variables['sf_model'][:]

   # Set up figure
    fig = plt.figure(figsize=(8,12))
    cmap=plt.cm.viridis
    levels = np.arange(15) * 2 - 4
    norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True)
    cmin,cmax=-5,30

    # Add model data to axis
    fig.add_subplot(3,1,1)
    plt.pcolormesh(dts, -z, sf_model.transpose(), 
                   vmin=cmin,vmax=cmax,cmap=cmap, norm=norm)
    plt.colorbar(orientation='vertical')
    plt.title('Overturning streamfunction at 26N in %s (model velocities)' % name)
    plt.xlabel('Dates')
    plt.ylabel('Depth (m)')

    # Add model data to axis (RAPID approx)
    fig.add_subplot(3,1,2)
    plt.pcolormesh(dts, -z, sf_rapid.transpose(), 
                   vmin=cmin,vmax=cmax,cmap=cmap, norm=norm)
    plt.colorbar(orientation='vertical')
    plt.title('Overturning streamfunction at 26N in %s (RAPID approx)' % name)
    plt.xlabel('Dates')
    plt.ylabel('Depth (m)')

    # Add optional observed data to axis
    if obs is not None:
        fig.add_subplot(3,1,3)
        plt.pcolormesh(obs.dates, -obs.z, obs.sf.transpose(), 
                       vmin=cmin,vmax=cmax, cmap=cmap, norm=norm)
        plt.colorbar(orientation='vertical')
        plt.title('Overturning streamfunction at 26N from RAPID array')
        plt.xlabel('Dates')
        plt.ylabel('Depth (m)')

    # Save plot
    plt.tight_layout()
    savef = basename + 'overturning_streamfunction_at_26n_hovmoller.png'
    print 'SAVING: %s' % savef
    fig.savefig(savef, resolution=300)
    plt.close()
项目:RapidMoc    作者:cdr30    | 项目源码 | 文件源码
def plot_streamfunction_hovmollers(trans, name='simulated', basename='', obs=None):
    """ Plot overturning stream function hovmoller diagrams"""

    # Extract variables from data objects
    dts = utils.get_ncdates(trans)
    z = trans.variables['depth'][:]
    sf_rapid = trans.variables['sf_rapid'][:]
    sf_model = trans.variables['sf_model'][:]

   # Set up figure
    fig = plt.figure(figsize=(8,12))
    cmap=plt.cm.viridis
    levels = np.arange(15) * 2 - 4
    norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True)
    cmin,cmax=-5,30

    # Add model data to axis
    fig.add_subplot(3,1,1)
    plt.pcolormesh(dts, -z, sf_model.transpose(), 
                   vmin=cmin,vmax=cmax,cmap=cmap, norm=norm)
    plt.colorbar(orientation='vertical')
    plt.title('Overturning streamfunction at 26N in %s (model velocities)' % name)
    plt.xlabel('Dates')
    plt.ylabel('Depth (m)')

    # Add model data to axis (RAPID approx)
    fig.add_subplot(3,1,2)
    plt.pcolormesh(dts, -z, sf_rapid.transpose(), 
                   vmin=cmin,vmax=cmax,cmap=cmap, norm=norm)
    plt.colorbar(orientation='vertical')
    plt.title('Overturning streamfunction at 26N in %s (RAPID approx)' % name)
    plt.xlabel('Dates')
    plt.ylabel('Depth (m)')

    # Add optional observed data to axis
    if obs is not None:
        fig.add_subplot(3,1,3)
        plt.pcolormesh(obs.dates, -obs.z, obs.sf.transpose(), 
                       vmin=cmin,vmax=cmax, cmap=cmap, norm=norm)
        plt.colorbar(orientation='vertical')
        plt.title('Overturning streamfunction at 26N from RAPID array')
        plt.xlabel('Dates')
        plt.ylabel('Depth (m)')

    # Save plot
    plt.tight_layout()
    savef = basename + 'overturning_streamfunction_at_26n_hovmoller.png'
    print 'SAVING: %s' % savef
    fig.savefig(savef, resolution=300)
    plt.close()