Python matplotlib.colors.Normalize() Examples

The following are 30 code examples of matplotlib.colors.Normalize(). 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: __init__.py    From dinosar with MIT License 8 votes vote down vote up
def make_coherence_cmap(
    mapname="inferno", vmin=1e-5, vmax=1, ncolors=64, outname="coherence-cog.cpt"
):
    """Write default colormap (coherence-cog.cpt) for isce coherence images.

    Parameters
    ----------
    mapname : str
        matplotlib colormap name
    vmin : float
        data value mapped to lower end of colormap
    vmax : float
        data value mapped to upper end of colormap
    ncolors : int
        number of discrete mapped values between vmin and vmax

    """
    cmap = plt.get_cmap(mapname)
    cNorm = colors.Normalize(vmin=vmin, vmax=vmax)
    scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=cmap)
    vals = np.linspace(vmin, vmax, ncolors, endpoint=True)

    write_cmap(outname, vals, scalarMap)

    return outname 
Example #2
Source File: axes3d.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def _shade_colors(self, color, normals):
        '''
        Shade *color* using normal vectors given by *normals*.
        *color* can also be an array of the same length as *normals*.
        '''

        shade = np.array([np.dot(n / proj3d.mod(n), [-1, -1, 0.5])
                          if proj3d.mod(n) else np.nan
                          for n in normals])
        mask = ~np.isnan(shade)

        if len(shade[mask]) > 0:
            norm = Normalize(min(shade[mask]), max(shade[mask]))
            shade[~mask] = min(shade[mask])
            color = mcolors.to_rgba_array(color)
            # shape of color should be (M, 4) (where M is number of faces)
            # shape of shade should be (M,)
            # colors should have final shape of (M, 4)
            alpha = color[:, 3]
            colors = (0.5 + norm(shade)[:, np.newaxis] * 0.5) * color
            colors[:, 3] = alpha
        else:
            colors = np.asanyarray(color).copy()

        return colors 
Example #3
Source File: xlsxpandasformatter.py    From xlsxpandasformatter with MIT License 6 votes vote down vote up
def convert_colormap_to_hex(cmap, x, vmin=0, vmax=1):
    """
    Example::
        >>> seaborn.palplot(seaborn.color_palette("RdBu_r", 7))
        >>> colorMapRGB = seaborn.color_palette("RdBu_r", 61)
        >>> colormap = seaborn.blend_palette(colorMapRGB, as_cmap=True, input='rgb')
        >>> [convert_colormap_to_hex(colormap, x, vmin=-2, vmax=2) for x in range(-2, 3)]
        ['#09386d', '#72b1d3', '#f7f6f5', '#e7866a', '#730421']
    """
    norm = colors.Normalize(vmin, vmax)
    color_rgb = plt.cm.get_cmap(cmap)(norm(x))
    color_hex = colors.rgb2hex(color_rgb)
    return color_hex 
Example #4
Source File: plot_functions.py    From ADNC with Apache License 2.0 6 votes vote down vote up
def plot_weightings(self, weightings, ax, name='Weightings', mode='log', color='YlOrRd'):
        assert weightings.shape.__len__() == 2, "plot weightings: need 2D matrix as data"
        if mode == 'log':
            norm = colors.LogNorm(vmin=1e-3, vmax=1)
        else:
            norm = colors.Normalize(vmin=0, vmax=1)
        img = ax.imshow(np.transpose(weightings), interpolation='nearest', norm=norm, cmap=color,
                        aspect='auto')  # gist_stern
        ax.set_adjustable('box-forced')
        if self.title:
            ax.set_ylabel(name, size=self.text_size)
        if self.legend:
            box = ax.get_position()
            ax.set_position([box.x0 - 0.001, box.y0, box.width, box.height])
            axColor = plt.axes([box.x0 + box.width + 0.005, box.y0, 0.005, box.height])
            cb = plt.colorbar(img, cax=axColor, orientation="vertical")
            for l in cb.ax.yaxis.get_ticklabels():
                l.set_size(self.text_size) 
Example #5
Source File: mpl_camera.py    From ctapipe with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def norm(self, norm):

        if norm == "lin":
            self.pixels.norm = Normalize()
        elif norm == "log":
            self.pixels.norm = LogNorm()
            self.pixels.autoscale()  # this is to handle matplotlib bug #5424
        elif norm == "symlog":
            self.pixels.norm = SymLogNorm(linthresh=1.0)
            self.pixels.autoscale()
        elif isinstance(norm, Normalize):
            self.pixels.norm = norm
        else:
            raise ValueError(
                "Unsupported norm: '{}', options are 'lin',"
                "'log','symlog', or a matplotlib Normalize object".format(norm)
            )

        self.update(force=True)
        self.pixels.autoscale() 
Example #6
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 #7
Source File: stress_gui.py    From fenics-topopt with MIT License 6 votes vote down vote up
def update(self, xPhys, u, title=None):
        """Plot to screen"""
        self.im.set_array(-xPhys.reshape((self.nelx, self.nely)).T)
        stress = self.stress_calculator.calculate_stress(xPhys, u, self.nu)
        # self.stress_calculator.calculate_fdiff_stress(xPhys, u, self.nu)
        self.myColorMap.set_norm(colors.Normalize(vmin=0, vmax=max(stress)))
        stress_rgba = self.myColorMap.to_rgba(stress)
        stress_rgba[:, :, 3] = xPhys.reshape(-1, 1)
        self.stress_im.set_array(np.swapaxes(
            stress_rgba.reshape((self.nelx, self.nely, 4)), 0, 1))
        self.fig.canvas.draw()
        self.fig.canvas.flush_events()
        if title is not None:
            plt.title(title)
        else:
            plt.xlabel("Max stress = {:.2f}".format(max(stress)[0]))
        plt.pause(0.01) 
Example #8
Source File: axes3d.py    From opticspy with MIT License 6 votes vote down vote up
def _shade_colors(self, color, normals):
        '''
        Shade *color* using normal vectors given by *normals*.
        *color* can also be an array of the same length as *normals*.
        '''

        shade = np.array([np.dot(n / proj3d.mod(n), [-1, -1, 0.5])
                          if proj3d.mod(n) else np.nan
                          for n in normals])
        mask = ~np.isnan(shade)

        if len(shade[mask]) > 0:
            norm = Normalize(min(shade[mask]), max(shade[mask]))
            shade[~mask] = min(shade[mask])
            color = colorConverter.to_rgba_array(color)
            # shape of color should be (M, 4) (where M is number of faces)
            # shape of shade should be (M,)
            # colors should have final shape of (M, 4)
            alpha = color[:, 3]
            colors = (0.5 + norm(shade)[:, np.newaxis] * 0.5) * color
            colors[:, 3] = alpha
        else:
            colors = np.asanyarray(color).copy()

        return colors 
Example #9
Source File: axes3d.py    From Computable with MIT License 6 votes vote down vote up
def _shade_colors(self, color, normals):
        '''
        Shade *color* using normal vectors given by *normals*.
        *color* can also be an array of the same length as *normals*.
        '''

        shade = np.array([np.dot(n / proj3d.mod(n), [-1, -1, 0.5])
                          for n in normals])
        mask = ~np.isnan(shade)

        if len(shade[mask]) > 0:
            norm = Normalize(min(shade[mask]), max(shade[mask]))
            color = colorConverter.to_rgba_array(color)
            # shape of color should be (M, 4) (where M is number of faces)
            # shape of shade should be (M,)
            # colors should have final shape of (M, 4)
            alpha = color[:, 3]
            colors = (0.5 + norm(shade)[:, np.newaxis] * 0.5) * color
            colors[:, 3] = alpha
        else:
            colors = np.asanyarray(color).copy()

        return colors 
Example #10
Source File: test_colors.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_Normalize():
    norm = mcolors.Normalize()
    vals = np.arange(-10, 10, 1, dtype=float)
    _inverse_tester(norm, vals)
    _scalar_tester(norm, vals)
    _mask_tester(norm, vals)

    # Handle integer input correctly (don't overflow when computing max-min,
    # i.e. 127-(-128) here).
    vals = np.array([-128, 127], dtype=np.int8)
    norm = mcolors.Normalize(vals.min(), vals.max())
    assert_array_equal(np.asarray(norm(vals)), [0, 1])

    # Don't lose precision on longdoubles (float128 on Linux):
    # for array inputs...
    vals = np.array([1.2345678901, 9.8765432109], dtype=np.longdouble)
    norm = mcolors.Normalize(vals.min(), vals.max())
    assert_array_equal(np.asarray(norm(vals)), [0, 1])
    # and for scalar ones.
    eps = np.finfo(np.longdouble).resolution
    norm = plt.Normalize(1, 1 + 100 * eps)
    # This returns exactly 0.5 when longdouble is extended precision (80-bit),
    # but only a value close to it when it is quadruple precision (128-bit).
    assert 0 < norm(1 + 50 * eps) < 1 
Example #11
Source File: plot_barycenter_fgw.py    From POT with MIT License 6 votes vote down vote up
def graph_colors(nx_graph, vmin=0, vmax=7):
    cnorm = mcol.Normalize(vmin=vmin, vmax=vmax)
    cpick = cm.ScalarMappable(norm=cnorm, cmap='viridis')
    cpick.set_array([])
    val_map = {}
    for k, v in nx.get_node_attributes(nx_graph, 'attr_name').items():
        val_map[k] = cpick.to_rgba(v)
    colors = []
    for node in nx_graph.nodes():
        colors.append(val_map[node])
    return colors

##############################################################################
# Generate data
# -------------

#%% circular dataset
# We build a dataset of noisy circular graphs.
# Noise is added on the structures by random connections and on the features by gaussian noise. 
Example #12
Source File: plot.py    From voxelmorph with GNU General Public License v3.0 6 votes vote down vote up
def flow_legend():
    """
    show quiver plot to indicate how arrows are colored in the flow() method.
    https://stackoverflow.com/questions/40026718/different-colours-for-arrows-in-quiver-plot
    """
    ph = np.linspace(0, 2*np.pi, 13)
    x = np.cos(ph)
    y = np.sin(ph)
    u = np.cos(ph)
    v = np.sin(ph)
    colors = np.arctan2(u, v)

    norm = Normalize()
    norm.autoscale(colors)
    # we need to normalize our colors array to match it colormap domain
    # which is [0, 1]

    colormap = cm.winter

    plt.figure(figsize=(6, 6))
    plt.xlim(-2, 2)
    plt.ylim(-2, 2)
    plt.quiver(x, y, u, v, color=colormap(norm(colors)),  angles='xy', scale_units='xy', scale=1)
    plt.show() 
Example #13
Source File: plot.py    From neuron with GNU General Public License v3.0 6 votes vote down vote up
def flow_legend():
    """
    show quiver plot to indicate how arrows are colored in the flow() method.
    https://stackoverflow.com/questions/40026718/different-colours-for-arrows-in-quiver-plot
    """
    ph = np.linspace(0, 2*np.pi, 13)
    x = np.cos(ph)
    y = np.sin(ph)
    u = np.cos(ph)
    v = np.sin(ph)
    colors = np.arctan2(u, v)

    norm = Normalize()
    norm.autoscale(colors)
    # we need to normalize our colors array to match it colormap domain
    # which is [0, 1]

    colormap = cm.winter

    plt.figure(figsize=(6, 6))
    plt.xlim(-2, 2)
    plt.ylim(-2, 2)
    plt.quiver(x, y, u, v, color=colormap(norm(colors)),  angles='xy', scale_units='xy', scale=1)
    plt.show() 
Example #14
Source File: dal_ros_aml.py    From dal with MIT License 6 votes vote down vote up
def update_gtl_plot(self,ax):
        # gtl = self.gt_likelihood.cpu().detach().numpy()
        gtl = self.gt_likelihood
        gtl, side = self.square_clock(gtl, self.grid_dirs)
        if self.obj_gtl == None:
            self.obj_gtl = ax.imshow(gtl,interpolation='nearest')
            ax.grid()
            ticks = np.linspace(0,self.grid_rows*side, side,endpoint=False)-0.5
            ax.set_yticks(ticks)
            ax.set_xticks(ticks)
            ax.tick_params(axis='y', labelleft='off')
            ax.tick_params(axis='x', labelbottom='off')
            ax.tick_params(bottom="off", left="off")
            ax.set_title('Target Likelihood')
        else:
            self.obj_gtl.set_data(gtl)
        self.obj_gtl.set_norm(norm = cm.Normalize().autoscale(gtl)) 
Example #15
Source File: dal_ros_aml.py    From dal with MIT License 6 votes vote down vote up
def update_prior_plot(self,ax):

        bel = np.copy(self.prior)
        bel,side = self.square_clock(bel, self.grid_dirs)
        if self.obj_bel_prior == None:
            self.obj_bel_prior = ax.imshow(bel,interpolation='nearest')
            ax.grid()
            ticks = np.linspace(0,self.grid_rows*side, side,endpoint=False)-0.5
            ax.set_yticks(ticks)
            ax.set_xticks(ticks)
            ax.tick_params(axis='y', labelleft='off')
            ax.tick_params(axis='x', labelbottom='off')
            ax.tick_params(bottom="off", left="off")
            ax.set_title('Prior (%.3f)'%self.prior.max())
        else:
            self.obj_bel_prior.set_data(bel)
            ax.set_title('Prior (%.3f)'%self.prior.max())

        self.obj_bel_prior.set_norm(norm = cm.Normalize().autoscale(bel)) 
Example #16
Source File: dal_ros_aml.py    From dal with MIT License 6 votes vote down vote up
def update_likely_plot(self,ax):
        lik = self.likelihood.cpu().detach().numpy()
        # if lik.min() == lik.max():
        #     lik *= 0
        # lik -= lik.min()
        # lik /= lik.max()
        lik, side = self.square_clock(lik, self.grid_dirs)
        # lik=self.circular_placement(lik, self.grid_dirs)
        # lik = lik.reshape(self.grid_rows*self.grid_dirs,self.grid_cols) 
        # lik = np.swapaxes(lik,0,1)
        # lik = lik.reshape(self.grid_rows, self.grid_dirs*self.grid_cols)
        # lik = np.concatenate((lik[0,:,:],lik[1,:,:],lik[2,:,:],lik[3,:,:]), axis=1)
        if self.obj_lik == None:
            self.obj_lik = ax.imshow(lik,interpolation='nearest')
            ax.grid()
            ticks = np.linspace(0,self.grid_rows*side, side,endpoint=False)-0.5
            ax.set_yticks(ticks)
            ax.set_xticks(ticks)
            ax.tick_params(axis='y', labelleft='off')
            ax.tick_params(axis='x', labelbottom='off')
            ax.tick_params(bottom="off", left="off")
            ax.set_title('Likelihood from NN')
        else:
            self.obj_lik.set_data(lik)
        self.obj_lik.set_norm(norm = cm.Normalize().autoscale(lik)) 
Example #17
Source File: dal_ros_aml.py    From dal with MIT License 6 votes vote down vote up
def update_likely_plot(self,ax):
        lik = self.likelihood.cpu().detach().numpy()
        # if lik.min() == lik.max():
        #     lik *= 0
        # lik -= lik.min()
        # lik /= lik.max()
        lik, side = square_clock(lik, self.grid_dirs)
        # lik=self.circular_placement(lik, self.grid_dirs)
        # lik = lik.reshape(self.grid_rows*self.grid_dirs,self.grid_cols) 
        # lik = np.swapaxes(lik,0,1)
        # lik = lik.reshape(self.grid_rows, self.grid_dirs*self.grid_cols)
        # lik = np.concatenate((lik[0,:,:],lik[1,:,:],lik[2,:,:],lik[3,:,:]), axis=1)
        if self.obj_lik == None:
            self.obj_lik = ax.imshow(lik,interpolation='nearest')
            ax.grid()
            ticks = np.linspace(0,self.grid_rows*side, side,endpoint=False)-0.5
            ax.set_yticks(ticks)
            ax.set_xticks(ticks)
            ax.tick_params(axis='y', labelleft='off')
            ax.tick_params(axis='x', labelbottom='off')
            ax.tick_params(bottom="off", left="off")
            ax.set_title('Likelihood from NN')
        else:
            self.obj_lik.set_data(lik)
        self.obj_lik.set_norm(norm = cm.Normalize().autoscale(lik)) 
Example #18
Source File: dal.py    From dal with MIT License 6 votes vote down vote up
def update_gtl_plot(self,ax):
        # gtl = self.gt_likelihood.cpu().detach().numpy()
        gtl = self.gt_likelihood
        gtl, side = square_clock(gtl, self.grid_dirs)
        if self.obj_gtl == None:
            self.obj_gtl = ax.imshow(gtl,interpolation='nearest')
            ax.grid()
            ticks = np.linspace(0,self.grid_rows*side, side,endpoint=False)-0.5
            ax.set_yticks(ticks)
            ax.set_xticks(ticks)
            ax.tick_params(axis='y', labelleft='off')
            ax.tick_params(axis='x', labelbottom='off')
            ax.tick_params(bottom="off", left="off")
            ax.set_title('Target Likelihood')
        else:
            self.obj_gtl.set_data(gtl)
        self.obj_gtl.set_norm(norm = cm.Normalize().autoscale(gtl)) 
Example #19
Source File: dal.py    From dal with MIT License 6 votes vote down vote up
def update_likely_plot(self,ax):
        lik = self.likelihood.cpu().detach().numpy()
        # if lik.min() == lik.max():
        #     lik *= 0
        # lik -= lik.min()
        # lik /= lik.max()
        lik, side = square_clock(lik, self.grid_dirs)
        # lik=self.circular_placement(lik, self.grid_dirs)
        # lik = lik.reshape(self.grid_rows*self.grid_dirs,self.grid_cols) 
        # lik = np.swapaxes(lik,0,1)
        # lik = lik.reshape(self.grid_rows, self.grid_dirs*self.grid_cols)
        # lik = np.concatenate((lik[0,:,:],lik[1,:,:],lik[2,:,:],lik[3,:,:]), axis=1)
        if self.obj_lik == None:
            self.obj_lik = ax.imshow(lik,interpolation='nearest')
            ax.grid()
            ticks = np.linspace(0,self.grid_rows*side, side,endpoint=False)-0.5
            ax.set_yticks(ticks)
            ax.set_xticks(ticks)
            ax.tick_params(axis='y', labelleft='off')
            ax.tick_params(axis='x', labelbottom='off')
            ax.tick_params(bottom="off", left="off")
            ax.set_title('Likelihood from NN')
        else:
            self.obj_lik.set_data(lik)
        self.obj_lik.set_norm(norm = cm.Normalize().autoscale(lik)) 
Example #20
Source File: axes3d.py    From matplotlib-4-abaqus with MIT License 6 votes vote down vote up
def _shade_colors(self, color, normals):
        '''
        Shade *color* using normal vectors given by *normals*.
        *color* can also be an array of the same length as *normals*.
        '''

        shade = np.array([np.dot(n / proj3d.mod(n), [-1, -1, 0.5])
                          for n in normals])
        mask = ~np.isnan(shade)

        if len(shade[mask]) > 0:
            norm = Normalize(min(shade[mask]), max(shade[mask]))
            color = colorConverter.to_rgba_array(color)
            # shape of color should be (M, 4) (where M is number of faces)
            # shape of shade should be (M,)
            # colors should have final shape of (M, 4)
            alpha = color[:, 3]
            colors = (0.5 + norm(shade)[:, np.newaxis] * 0.5) * color
            colors[:, 3] = alpha
        else:
            colors = np.asanyarray(color).copy()

        return colors 
Example #21
Source File: stress_gui.py    From fenics-topopt with MIT License 6 votes vote down vote up
def update(self, xPhys, u, title=None):
        """Plot to screen"""
        self.im.set_array(-xPhys.reshape((self.nelx, self.nely)).T)
        stress = self.stress_calculator.calculate_stress(xPhys, u, self.nu)
        # self.stress_calculator.calculate_fdiff_stress(xPhys, u, self.nu)
        self.myColorMap.set_norm(colors.Normalize(vmin=0, vmax=max(stress)))
        stress_rgba = self.myColorMap.to_rgba(stress)
        stress_rgba[:, :, 3] = xPhys.reshape(-1, 1)
        self.stress_im.set_array(np.swapaxes(
            stress_rgba.reshape((self.nelx, self.nely, 4)), 0, 1))
        self.fig.canvas.draw()
        self.fig.canvas.flush_events()
        if title is not None:
            plt.title(title)
        else:
            plt.xlabel("Max stress = {:.2f}".format(max(stress)[0]))
        plt.pause(0.01) 
Example #22
Source File: dal_ros_aml.py    From dal with MIT License 5 votes vote down vote up
def update_belief_plot(self,ax):
        bel = self.belief.cpu().detach().numpy()
        # if bel.min() == bel.max():
        #     bel *= 0
        # bel -= bel.min()
        # bel /= bel.max()
        bel,side = self.square_clock(bel, self.grid_dirs)
        #bel=self.circular_placement(bel, self.grid_dirs)
        # bel = bel.reshape(self.grid_rows*self.grid_dirs,self.grid_cols) 
        # bel = np.swapaxes(bel,0,1)
        # bel = bel.reshape(self.grid_rows,self.grid_dirs*self.grid_cols) 
        # bel = np.concatenate((bel[0,:,:],bel[1,:,:],bel[2,:,:],bel[3,:,:]), axis=1)
        if self.obj_bel == None:
            self.obj_bel = ax.imshow(bel,interpolation='nearest')
            ax.grid()
            ticks = np.linspace(0,self.grid_rows*side, side,endpoint=False)-0.5
            ax.set_yticks(ticks)
            ax.set_xticks(ticks)
            ax.tick_params(axis='y', labelleft='off')
            ax.tick_params(axis='x', labelbottom='off')
            ax.tick_params(bottom="off", left="off")
            ax.set_title('Belief (%.3f)'%self.belief.cpu().detach().numpy().max())
            
        else:
            self.obj_bel.set_data(bel)
            ax.set_title('Belief (%.3f)'%self.belief.cpu().detach().numpy().max())

        self.obj_bel.set_norm(norm = cm.Normalize().autoscale(bel)) 
Example #23
Source File: cm.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def set_norm(self, norm):
        """Set the normalization instance.

        Parameters
        ----------
        norm : `.Normalize`
        """
        if norm is None:
            norm = colors.Normalize()
        self.norm = norm
        self.changed() 
Example #24
Source File: dal.py    From dal with MIT License 5 votes vote down vote up
def update_belief_plot(self,ax):
        bel = self.belief.cpu().detach().numpy()
        # if bel.min() == bel.max():
        #     bel *= 0
        # bel -= bel.min()
        # bel /= bel.max()
        bel,side = square_clock(bel, self.grid_dirs)
        #bel=self.circular_placement(bel, self.grid_dirs)
        # bel = bel.reshape(self.grid_rows*self.grid_dirs,self.grid_cols) 
        # bel = np.swapaxes(bel,0,1)
        # bel = bel.reshape(self.grid_rows,self.grid_dirs*self.grid_cols) 
        # bel = np.concatenate((bel[0,:,:],bel[1,:,:],bel[2,:,:],bel[3,:,:]), axis=1)
        if self.obj_bel == None:
            self.obj_bel = ax.imshow(bel,interpolation='nearest')
            ax.grid()
            ticks = np.linspace(0,self.grid_rows*side, side,endpoint=False)-0.5
            ax.set_yticks(ticks)
            ax.set_xticks(ticks)
            ax.tick_params(axis='y', labelleft='off')
            ax.tick_params(axis='x', labelbottom='off')
            ax.tick_params(bottom="off", left="off")
            ax.set_title('Belief (%.3f)'%self.belief.cpu().detach().numpy().max())
            
        else:
            self.obj_bel.set_data(bel)
            ax.set_title('Belief (%.3f)'%self.belief.cpu().detach().numpy().max())

        self.obj_bel.set_norm(norm = cm.Normalize().autoscale(bel)) 
Example #25
Source File: dal_ros_aml.py    From dal with MIT License 5 votes vote down vote up
def update_belief_plot(self,ax):
        bel = self.belief.cpu().detach().numpy()
        # if bel.min() == bel.max():
        #     bel *= 0
        # bel -= bel.min()
        # bel /= bel.max()
        bel,side = square_clock(bel, self.grid_dirs)
        #bel=self.circular_placement(bel, self.grid_dirs)
        # bel = bel.reshape(self.grid_rows*self.grid_dirs,self.grid_cols) 
        # bel = np.swapaxes(bel,0,1)
        # bel = bel.reshape(self.grid_rows,self.grid_dirs*self.grid_cols) 
        # bel = np.concatenate((bel[0,:,:],bel[1,:,:],bel[2,:,:],bel[3,:,:]), axis=1)
        if self.obj_bel == None:
            self.obj_bel = ax.imshow(bel,interpolation='nearest')
            ax.grid()
            ticks = np.linspace(0,self.grid_rows*side, side,endpoint=False)-0.5
            ax.set_yticks(ticks)
            ax.set_xticks(ticks)
            ax.tick_params(axis='y', labelleft='off')
            ax.tick_params(axis='x', labelbottom='off')
            ax.tick_params(bottom="off", left="off")
            ax.set_title('Belief (%.3f)'%self.belief.cpu().detach().numpy().max())
            
        else:
            self.obj_bel.set_data(bel)
            ax.set_title('Belief (%.3f)'%self.belief.cpu().detach().numpy().max())

        self.obj_bel.set_norm(norm = cm.Normalize().autoscale(bel)) 
Example #26
Source File: mpl_camera.py    From ctapipe with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def norm(self):
        """
        The norm instance of the Display

        Possible values:

        - "lin": linear scale
        - "log": log scale (cannot have negative values)
        - "symlog": symmetric log scale (negative values are ok)
        -  any matplotlib.colors.Normalize instance, e. g. PowerNorm(gamma=-2)
        """
        return self.pixels.norm 
Example #27
Source File: util.py    From raster-deep-learning with Apache License 2.0 5 votes vote down vote up
def get_cmap(N):
    color_norm  = mcolors.Normalize(vmin=0, vmax=N-1)
    return cmx.ScalarMappable(norm=color_norm, cmap='Set3').to_rgba 
Example #28
Source File: explore_mapper.py    From mapper-tda with MIT License 5 votes vote down vote up
def _get_colors(self, dic, cmap_str='brg'):

        cNorm  = colors.Normalize(vmin=min(self.filtered_values), vmax=max(self.filtered_values))
        scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=plt.get_cmap(cmap_str))

        node_color_dic = {}
        for _, clusters in dic.items():
            for node, indices in clusters.items():
                mitjana = np.mean(self.filtered_values[indices])
                node_color_dic[node] = scalarMap.to_rgba(mitjana)

        return node_color_dic, scalarMap 
Example #29
Source File: art3d.py    From opticspy with MIT License 5 votes vote down vote up
def zalpha(colors, zs):
    """Modify the alphas of the color list according to depth"""
    # FIXME: This only works well if the points for *zs* are well-spaced
    #        in all three dimensions. Otherwise, at certain orientations,
    #        the min and max zs are very close together.
    #        Should really normalize against the viewing depth.
    colors = get_colors(colors, len(zs))
    if zs.size > 0 :
        norm = Normalize(min(zs), max(zs))
        sats = 1 - norm(zs) * 0.7
        colors = [(c[0], c[1], c[2], c[3] * s) for c, s in zip(colors, sats)]
    return colors 
Example #30
Source File: plot_functions.py    From ADNC with Apache License 2.0 5 votes vote down vote up
def plot_matrix(self, matrix, ax, name='Weightings', mode='norm', color='RdYlBu', zero_width=5, zero_add='zeros'):
        assert matrix.shape.__len__() == 3, "plot weightings: need 3D matrix as data"

        if mode == 'log':
            norm = colors.LogNorm(vmin=1e-8, vmax=0.1)
        elif mode == 'norm1':
            norm = colors.Normalize(vmin=0, vmax=1)
        else:
            norm = colors.Normalize(vmin=-1, vmax=1)

        if zero_add == 'zeros':
            matrix = np.concatenate([matrix, np.zeros([matrix.shape[0], matrix.shape[1], zero_width])], axis=2)
            matrix = np.transpose(matrix, axes=(0, 2, 1))
            flat_matrix = np.reshape(matrix, [-1, matrix.shape[2]])
            flat_matrix = np.concatenate([np.zeros([zero_width, flat_matrix.shape[1]]), flat_matrix], axis=0)
        else:
            matrix = np.concatenate([matrix, np.ones([matrix.shape[0], matrix.shape[1], zero_width])], axis=2)
            matrix = np.transpose(matrix, axes=(0, 2, 1))
            flat_matrix = np.reshape(matrix, [-1, matrix.shape[2]])
            flat_matrix = np.concatenate([np.ones([zero_width, flat_matrix.shape[1]]), flat_matrix], axis=0)

        img = ax.imshow(np.transpose(flat_matrix), aspect='auto', interpolation='nearest', norm=norm, cmap=color)

        ax.set_adjustable('box-forced')
        if self.title:
            ax.set_ylabel(name, size=self.text_size)
        if self.legend:
            box = ax.get_position()
            ax.set_position([box.x0 - 0.001, box.y0, box.width, box.height])
            axColor = plt.axes([box.x0 + box.width + 0.005, box.y0, 0.005, box.height])
            cb = plt.colorbar(img, cax=axColor, orientation="vertical")
            for l in cb.ax.yaxis.get_ticklabels():
                l.set_size(self.text_size)
            tick_locator = ticker.MaxNLocator(nbins=3)
            cb.locator = tick_locator
            cb.update_ticks()