Python matplotlib.colors.BoundaryNorm() Examples

The following are 30 code examples of matplotlib.colors.BoundaryNorm(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module matplotlib.colors , or try the search function .
Example #1
Source File: test_colorbar.py    From twitter-stock-recommendation with MIT License 6 votes vote down vote up
def _get_cmap_norms():
    """
    Define a colormap and appropriate norms for each of the four
    possible settings of the extend keyword.

    Helper function for _colorbar_extension_shape and
    colorbar_extension_length.
    """
    # Create a color map and specify the levels it represents.
    cmap = get_cmap("RdBu", lut=5)
    clevs = [-5., -2.5, -.5, .5, 1.5, 3.5]
    # Define norms for the color maps.
    norms = dict()
    norms['neither'] = BoundaryNorm(clevs, len(clevs) - 1)
    norms['min'] = BoundaryNorm([-10] + clevs[1:], len(clevs) - 1)
    norms['max'] = BoundaryNorm(clevs[:-1] + [10], len(clevs) - 1)
    norms['both'] = BoundaryNorm([-10] + clevs[1:-1] + [10], len(clevs) - 1)
    return cmap, norms 
Example #2
Source File: colorbar.py    From Computable with MIT License 6 votes vote down vote up
def _select_locator(self, formatter):
        '''
        select a suitable locator
        '''
        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(nbins=5)
        else:
            b = self._boundaries[self._inside]
            locator = ticker.FixedLocator(b) #, nbins=10)

        self.cbar_axis.set_major_locator(locator) 
Example #3
Source File: display.py    From pycpt with GNU General Public License v2.0 6 votes vote down vote up
def plot_colormap(cmap, continuous=True, discrete=True, ndisc=9):
    """Make a figure displaying the color map in continuous and/or discrete form
    """
    nplots = int(continuous) + int(discrete)
    fig, axx = plt.subplots(figsize=(6,.5*nplots), nrows=nplots, frameon=False)
    axx = np.asarray(axx)
    i=0
    if continuous:
        norm = mcolors.Normalize(vmin=0, vmax=1)
        ColorbarBase(axx.flat[i], cmap=cmap, norm=norm, orientation='horizontal') ; i+=1
    if discrete:
        colors = cmap(np.linspace(0, 1, ndisc))
        cmap_d = mcolors.ListedColormap(colors, name=cmap.name)
        norm = mcolors.BoundaryNorm(np.linspace(0, 1, ndisc+1), len(colors))
        ColorbarBase(axx.flat[i], cmap=cmap_d, norm=norm, orientation='horizontal')
    for ax in axx.flat:
        ax.set_axis_off()
    fig.text(0.95, 0.5, cmap.name, va='center', ha='left', fontsize=12) 
Example #4
Source File: colorbar.py    From matplotlib-4-abaqus with MIT License 6 votes vote down vote up
def _select_locator(self, formatter):
        '''
        select a suitable locator
        '''
        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(nbins=5)
        else:
            b = self._boundaries[self._inside]
            locator = ticker.FixedLocator(b) #, nbins=10)

        self.cbar_axis.set_major_locator(locator) 
Example #5
Source File: test_colorbar.py    From neural-network-animation with MIT License 6 votes vote down vote up
def _get_cmap_norms():
    """
    Define a colormap and appropriate norms for each of the four
    possible settings of the extend keyword.

    Helper function for _colorbar_extension_shape and
    colorbar_extension_length.
    """
    # Create a color map and specify the levels it represents.
    cmap = get_cmap("RdBu", lut=5)
    clevs = [-5., -2.5, -.5, .5, 1.5, 3.5]
    # Define norms for the color maps.
    norms = dict()
    norms['neither'] = BoundaryNorm(clevs, len(clevs) - 1)
    norms['min'] = BoundaryNorm([-10] + clevs[1:], len(clevs) - 1)
    norms['max'] = BoundaryNorm(clevs[:-1] + [10], len(clevs) - 1)
    norms['both'] = BoundaryNorm([-10] + clevs[1:-1] + [10], len(clevs) - 1)
    return cmap, norms 
Example #6
Source File: colorbar.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def _get_ticker_locator_formatter(self):
        """
        This code looks at the norm being used by the colorbar
        and decides what locator and formatter to use.  If ``locator`` has
        already been set by hand, it just returns
        ``self.locator, self.formatter``.
        """
        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 = _ColorbarLogLocator(self)
                elif isinstance(self.norm, colors.SymLogNorm):
                    # The subs setting here should be replaced
                    # by logic in the locator.
                    locator = ticker.SymmetricalLogLocator(
                                      subs=np.arange(1, 10),
                                      linthresh=self.norm.linthresh,
                                      base=10)
                else:
                    if mpl.rcParams['_internal.classic_mode']:
                        locator = ticker.MaxNLocator()
                    else:
                        locator = _ColorbarAutoLocator(self)
            else:
                b = self._boundaries[self._inside]
                locator = ticker.FixedLocator(b, nbins=10)
        _log.debug('locator: %r', locator)
        return locator, formatter 
Example #7
Source File: colorbar.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def _select_locator(self, formatter):
        '''
        select a suitable locator
        '''
        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(nbins=5)
        else:
            b = self._boundaries[self._inside]
            locator = ticker.FixedLocator(b) #, nbins=10)

        self.cbar_axis.set_major_locator(locator) 
Example #8
Source File: test_colorbar.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _get_cmap_norms():
    """
    Define a colormap and appropriate norms for each of the four
    possible settings of the extend keyword.

    Helper function for _colorbar_extension_shape and
    colorbar_extension_length.
    """
    # Create a color map and specify the levels it represents.
    cmap = get_cmap("RdBu", lut=5)
    clevs = [-5., -2.5, -.5, .5, 1.5, 3.5]
    # Define norms for the color maps.
    norms = dict()
    norms['neither'] = BoundaryNorm(clevs, len(clevs) - 1)
    norms['min'] = BoundaryNorm([-10] + clevs[1:], len(clevs) - 1)
    norms['max'] = BoundaryNorm(clevs[:-1] + [10], len(clevs) - 1)
    norms['both'] = BoundaryNorm([-10] + clevs[1:-1] + [10], len(clevs) - 1)
    return cmap, norms 
Example #9
Source File: main.py    From youtube with GNU General Public License v3.0 6 votes vote down vote up
def plot_slic(array, clusters, K, S, output_figure = ''):
    fig = plt.figure(figsize=(8, 6))
    # create colormap based on cluster RGB centers
    slic_colormap = []
    for c in clusters:
        slic_colormap.append((c[0], c[1], c[2], 1.0))
    slic_listed_colormap = ListedColormap(slic_colormap)
    slic_norm = BoundaryNorm(range(K), K)
    plt.imshow(array, norm=slic_norm, cmap=slic_listed_colormap)
    # adjust image
    (rows, columns) = array.shape
    plt.xlim([0 - S, columns + S])
    plt.ylim([0 - S, rows + S])

    if output_figure != '':
        plt.savefig(output_figure, format='png', dpi=1000)
    else:
        plt.show()

# open dataset 
Example #10
Source File: instance_attention.py    From Scale-Adaptive-Network with MIT License 6 votes vote down vote up
def show(self, image, label_1s, label_2s, label_3s, label, label_at):
        import matplotlib.pyplot as plt
        from matplotlib import colors
        # make a color map of fixed colors
        cmap = colors.ListedColormap([(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)])
        bounds=[0,1,2,3,4,5,6,7]
        norm = colors.BoundaryNorm(bounds, cmap.N)

        fig, axes = plt.subplots(2,3)
        (ax1, ax2, ax3), (ax4, ax5, ax6) = axes
        ax1.set_title('image'); ax1.imshow(image)
        ax3.set_title('label'); ax2.imshow(label, cmap=cmap, norm=norm)
        ax3.set_title('label 1s'); ax3.imshow(label_1s, cmap=cmap, norm=norm)
        ax4.set_title('label 2s'); ax4.imshow(label_2s, cmap=cmap, norm=norm)
        ax5.set_title('label 3s'); ax5.imshow(label_3s, cmap=cmap, norm=norm)
        ax6.set_title('label at'); ax6.imshow(label_at, cmap=cmap, norm=norm)
        plt.show() 
Example #11
Source File: part_attention.py    From Scale-Adaptive-Network with MIT License 6 votes vote down vote up
def show(self, image, label_1s, label_2s, label_3s, label, label_at):
        import matplotlib.pyplot as plt
        from matplotlib import colors
        # make a color map of fixed colors
        cmap = colors.ListedColormap([(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)])
        bounds=[0,1,2,3,4,5,6,7]
        norm = colors.BoundaryNorm(bounds, cmap.N)

        fig, axes = plt.subplots(2,3)
        (ax1, ax2, ax3), (ax4, ax5, ax6) = axes
        ax1.set_title('image'); ax1.imshow(image)
        ax3.set_title('label'); ax2.imshow(label, cmap=cmap, norm=norm)
        ax3.set_title('label 1s'); ax3.imshow(label_1s, cmap=cmap, norm=norm)
        ax4.set_title('label 2s'); ax4.imshow(label_2s, cmap=cmap, norm=norm)
        ax5.set_title('label 3s'); ax5.imshow(label_3s, cmap=cmap, norm=norm)
        ax6.set_title('label at'); ax6.imshow(label_at, cmap=cmap, norm=norm)
        plt.show() 
Example #12
Source File: test_colorbar.py    From coffeegrindsize with MIT License 6 votes vote down vote up
def _get_cmap_norms():
    """
    Define a colormap and appropriate norms for each of the four
    possible settings of the extend keyword.

    Helper function for _colorbar_extension_shape and
    colorbar_extension_length.
    """
    # Create a color map and specify the levels it represents.
    cmap = get_cmap("RdBu", lut=5)
    clevs = [-5., -2.5, -.5, .5, 1.5, 3.5]
    # Define norms for the color maps.
    norms = dict()
    norms['neither'] = BoundaryNorm(clevs, len(clevs) - 1)
    norms['min'] = BoundaryNorm([-10] + clevs[1:], len(clevs) - 1)
    norms['max'] = BoundaryNorm(clevs[:-1] + [10], len(clevs) - 1)
    norms['both'] = BoundaryNorm([-10] + clevs[1:-1] + [10], len(clevs) - 1)
    return cmap, norms 
Example #13
Source File: colorbar.py    From CogAlg with MIT License 6 votes vote down vote up
def _select_locator(self, formatter):
        '''
        select a suitable locator
        '''
        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(nbins=5)
        else:
            b = self._boundaries[self._inside]
            locator = ticker.FixedLocator(b)

        self.cbar_axis.set_major_locator(locator) 
Example #14
Source File: colorbar.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
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())
            y = np.ma.filled(y, np.nan)
        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
        elif self.extend == 'both':
            # Exclude leftmost and rightmost intervals in y.
            clen = y[-2] - y[1]
            automin = (y[2] - y[1]) / clen
            automax = (y[-2] - y[-3]) / clen
        if self.extend in ('both', 'min', 'max'):
            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] = np.ma.filled(norm(yi), np.nan)
        return y 
Example #15
Source File: colorbar.py    From CogAlg with MIT License 5 votes vote down vote up
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()

        bunique = b
        yunique = self._y
        # trim extra b values at beginning and end if they are
        # not unique.  These are here for extended colorbars, and are not
        # wanted for the interpolation.
        if b[0] == b[1]:
            bunique = bunique[1:]
            yunique = yunique[1:]
        if b[-1] == b[-2]:
            bunique = bunique[:-1]
            yunique = yunique[:-1]

        z = np.interp(xn, bunique, yunique)
        return z 
Example #16
Source File: colorbar.py    From CogAlg with MIT License 5 votes vote down vote up
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())
            y = np.ma.filled(y, np.nan)
        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
        elif self.extend == 'both':
            # Exclude leftmost and rightmost intervals in y.
            clen = y[-2] - y[1]
            automin = (y[2] - y[1]) / clen
            automax = (y[-2] - y[-3]) / clen
        if self.extend in ('both', 'min', 'max'):
            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] = np.ma.filled(norm(yi), np.nan)
        return y 
Example #17
Source File: evaluate.py    From DSRG with MIT License 5 votes vote down vote up
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() 
Example #18
Source File: colorbar.py    From Computable with MIT License 5 votes vote down vote up
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 
Example #19
Source File: cmap.py    From artview with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def update_colormap(self):
        '''Get colormap from GUI.'''
        self.cmap['lock'] = self.lock_box.isChecked()
        idx = self.norm_type.currentIndex()

        self.cmap['vmin'] = float(self.ent_vmin.text())
        self.cmap['vmax'] = float(self.ent_vmax.text())

        if idx == 0:
            self.cmap['norm'] = None
        elif idx == 1:
            self.cmap['norm'] = colors.Normalize(vmin=self.cmap['vmin'],
                                                 vmax=self.cmap['vmax'])
        elif idx == 2:
            self.cmap['norm'] = colors.LogNorm(vmin=self.cmap['vmin'],
                                               vmax=self.cmap['vmax'])
        elif idx == 3:
            self.cmap['norm'] = colors.SymLogNorm(
                linthresh=float(self.ent_linthresh.text()),
                linscale=float(self.ent_linscale.text()),
                vmin=self.cmap['vmin'],
                vmax=self.cmap['vmax'])
        elif idx == 4:
            self.cmap['norm'] = colors.PowerNorm(
                gamma=float(self.ent_gamma.text()),
                vmin=self.cmap['vmin'],
                vmax=self.cmap['vmax'])
        elif idx == 5:
            bounds = self.get_bounds()
            self.cmap['norm'] = colors.BoundaryNorm(bounds,
                                                    ncolors=256)
        self.plot() 
Example #20
Source File: cmap.py    From artview with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot(self):
        '''Replot the colorbar.'''
        if self.cmap is None:
            return

        self.ax.cla()
        self.cax.cla()
        cmap = self.cmap
        if 'norm' not in cmap or cmap['norm'] is None:
            self.norm_type.setCurrentIndex(0)
        else:
            norm_name = cmap['norm'].__class__.__name__
            if norm_name == 'Normalize':
                self.norm_type.setCurrentIndex(1)
            elif norm_name == 'LogNorm':
                self.norm_type.setCurrentIndex(2)
            elif norm_name == 'SymLogNorm':
                self.norm_type.setCurrentIndex(3)
            elif norm_name == 'PowerNorm':
                self.norm_type.setCurrentIndex(4)
            elif norm_name == 'BoundaryNorm':
                self.norm_type.setCurrentIndex(5)

        if cmap is not None:
            if 'norm' in cmap:
                norm = cmap['norm']
            else:
                norm = None
            im = self.ax.imshow(gradient, aspect='auto', cmap=cmap['cmap'],
                                vmin=cmap['vmin'], vmax=cmap['vmax'],
                                norm=norm)
            plt.colorbar(im, cax=self.cax)

        self.canvas.draw() 
Example #21
Source File: test_colors.py    From ImageFusion with MIT License 5 votes vote down vote up
def test_BoundaryNorm():
    """
    Github issue #1258: interpolation was failing with numpy
    1.7 pre-release.
    """
    # TODO: expand this into a more general test of BoundaryNorm.
    boundaries = [0, 1.1, 2.2]
    vals = [-1, 0, 2, 2.2, 4]
    expected = [-1, 0, 2, 3, 3]
    # ncolors != len(boundaries) - 1 triggers interpolation
    ncolors = len(boundaries)
    bn = mcolors.BoundaryNorm(boundaries, ncolors)
    assert_array_equal(bn(vals), expected) 
Example #22
Source File: colorbar.py    From ImageFusion with MIT License 5 votes vote down vote up
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.
        ii = np.searchsorted(b, xn)
        i0 = ii - 1
        itop = (ii == len(b))
        ibot = (ii == 0)
        i0[itop] -= 1
        ii[itop] -= 1
        i0[ibot] += 1
        ii[ibot] += 1

        db = np.take(b, ii) - np.take(b, i0)
        y = self._y
        dy = np.take(y, ii) - np.take(y, i0)
        z = np.take(y, i0) + (xn - np.take(b, i0)) * dy / db
        return z 
Example #23
Source File: colorbar.py    From ImageFusion with MIT License 5 votes vote down vote up
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 
Example #24
Source File: data_class.py    From MIDI-VAE with MIT License 5 votes vote down vote up
def draw_difference_pianoroll(original, predicted, name_1='Original', name_2='Predicted', show=False, save_path=''):

    if original.shape!=predicted.shape:
        print("Shape mismatch. Not drawing a plot.")
        return

    draw_matrix = original + 2 * predicted
    
    cm = colors.ListedColormap(['white', 'blue', 'red', 'black'])
    bounds=[0,1,2,3,4]
    n = colors.BoundaryNorm(bounds, cm.N)

    original_color = cm(1/3)
    predicted_color = cm(2/3)
    both_color = cm(1.0)

    original_patch = mpatches.Patch(color=original_color, label=name_1)
    predicted_patch = mpatches.Patch(color=predicted_color, label=name_2)
    both_patch = mpatches.Patch(color=both_color, label='Notes in both songs')

    plt.figure(figsize=(20.0, 10.0))
    plt.title('Difference-Pitch-plot of ' + name_1 + ' and ' + name_2, fontsize=10)
    plt.legend(handles=[original_patch, predicted_patch, both_patch], loc='upper right', prop={'size': 8})

    plt.pcolor(draw_matrix, cmap=cm, vmin=0, vmax=3, norm=n)
    if show:
        plt.show()
    if len(save_path) > 0:
        plt.savefig(save_path)
        tikz_save(save_path + ".tex", encoding='utf-8', show_info=False)
        
    plt.close() 
Example #25
Source File: palettes.py    From scvelo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _plot_color_cylce(clists: Mapping[str, Sequence[str]]):
    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.colors import ListedColormap, BoundaryNorm

    fig, axes = plt.subplots(nrows=len(clists))  # type: plt.Figure, plt.Axes
    fig.subplots_adjust(top=0.95, bottom=0.01, left=0.3, right=0.99)
    axes[0].set_title("Color Maps/Cycles", fontsize=14)

    for ax, (name, clist) in zip(axes, clists.items()):
        n = len(clist)
        ax.imshow(
            np.arange(n)[None, :].repeat(2, 0),
            aspect="auto",
            cmap=ListedColormap(clist),
            norm=BoundaryNorm(np.arange(n + 1) - 0.5, n),
        )
        pos = list(ax.get_position().bounds)
        x_text = pos[0] - 0.01
        y_text = pos[1] + pos[3] / 2.0
        fig.text(x_text, y_text, name, va="center", ha="right", fontsize=10)

    # Turn off all ticks & spines
    for ax in axes:
        ax.set_axis_off()
    fig.show() 
Example #26
Source File: evaluate.py    From Pytorch-Deeplab with MIT License 5 votes vote down vote up
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() 
Example #27
Source File: evaluate_msc.py    From Pytorch-Deeplab with MIT License 5 votes vote down vote up
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() 
Example #28
Source File: colorbar.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
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 
Example #29
Source File: modify.py    From pycpt with GNU General Public License v2.0 5 votes vote down vote up
def generate_cmap_norm(levels, cm, extend='neither', name='from_list', return_dict=False):
    """Generate a color map and norm from levels and a colormap (name)
    
    Parameters
    ----------
    levels : iterable of levels
        data levels
    cm : cmap or name of registered cmap
        color map
    extend : str [ neither | both | min | max ]
        which edge(s) of the color range to extend
    name : str, optional
        new name for colormap
    return_dict : bool
        return dictionary
    """
    if isinstance(cm, str):
        cm = plt.get_cmap(cm)
    nplus = [-1,0,0,1][['neither','min','max','both'].index(extend)]
    N = len(levels) + nplus
    colors = cm(np.linspace(0, 1, N))
    cmap = mcolors.ListedColormap(colors, name=(name or cm.name))
    if extend in ['min', 'both']:
        cmap.set_under(colors[0])
    else:
        cmap.set_under('none')
    if extend in ['max', 'both']:
        cmap.set_over(colors[-1])
    else:
        cmap.set_over('none')
    cmap.colorbar_extend = extend
    norm = mcolors.BoundaryNorm(levels, N)
    if return_dict:
        return dict(cmap=cmap, norm=norm)
    else:
        return cmap, norm 
Example #30
Source File: get_attention_of_branches.py    From Scale-Adaptive-Network with MIT License 5 votes vote down vote up
def handle_three_branches(self, im, result, final, op_1s, op_2s, op_3s):
        fig, axes = plt.subplots(2, 3)
        (ax1, ax2, ax3), (ax4, ax5, ax6) = axes
        fig.set_size_inches(16, 8, forward=True)

        ax1.set_title('im')
        ax1.imshow(im)

        # make a color map of fixed colors
        cmap = colors.ListedColormap([(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)])
        bounds=[0,1,2,3,4,5,6,7]
        norm = colors.BoundaryNorm(bounds, cmap.N)
        ax2.set_title('prediction')
        ax2.imshow(result, cmap=cmap, norm=norm)

        ax3.set_title('branch_1s')
        im1 = ax3.imshow(op_1s)
        divider3 = make_axes_locatable(ax3)
        cax3 = divider3.append_axes("right", size="5%", pad=0.05)
        plt.colorbar(im1, cax=cax3)

        ax4.set_title('branch_2s')
        im2 = ax4.imshow(op_2s)
        divider4 = make_axes_locatable(ax4)
        cax4 = divider4.append_axes("right", size="5%", pad=0.05)
        plt.colorbar(im2, cax=cax4)

        ax5.set_title('branch_3s')
        im3 = ax5.imshow(op_3s)
        divider5 = make_axes_locatable(ax5)
        cax5 = divider5.append_axes("right", size="5%", pad=0.05)
        plt.colorbar(im3, cax=cax5)

        ax6.set_title('final output')
        fl = ax6.imshow(final, vmin=0, vmax=1)
        divider6 = make_axes_locatable(ax6)
        cax6 = divider6.append_axes("right", size="5%", pad=0.05)
        plt.colorbar(fl, cax=cax6)

        #plt.show()
        return fig