Python matplotlib.cm.ScalarMappable() Examples

The following are 30 code examples for showing how to use matplotlib.cm.ScalarMappable(). These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.

You may also want to check out all available functions/classes of the module matplotlib.cm , or try the search function .

Example 1
Project: dinosar   Author: scottyhq   File: __init__.py    License: MIT License 6 votes vote down vote up
def write_cmap(outname, vals, scalarMap):
    """Write external cpt colormap file based on matplotlib colormap.

    Parameters
    ----------
    outname : str
        name of output file (e.g. amplitude-cog.cpt)
    vals : float
        values to be mapped to ncolors
    scalarMap: ScalarMappable
        mapping between array value and colormap value between 0 and 1

    """
    with open(outname, "w") as fid:
        for val in vals:
            cval = scalarMap.to_rgba(val)
            fid.write(
                "{0} {1} {2} {3} \n".format(
                    val,  # value
                    int(cval[0] * 255),  # R
                    int(cval[1] * 255),  # G
                    int(cval[2] * 255),
                )
            )  # B
        fid.write("nv 0 0 0 0 \n")  # nodata alpha transparency 
Example 2
Project: dinosar   Author: scottyhq   File: __init__.py    License: MIT License 6 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 3
Project: Computable   Author: ktraunmueller   File: image.py    License: MIT License 6 votes vote down vote up
def __init__(self, fig,
                 cmap=None,
                 norm=None,
                 offsetx=0,
                 offsety=0,
                 origin=None,
                 **kwargs
                 ):

        """
        cmap is a colors.Colormap instance
        norm is a colors.Normalize instance to map luminance to 0-1

        kwargs are an optional list of Artist keyword args
        """
        martist.Artist.__init__(self)
        cm.ScalarMappable.__init__(self, norm, cmap)
        if origin is None:
            origin = rcParams['image.origin']
        self.origin = origin
        self.figure = fig
        self.ox = offsetx
        self.oy = offsety
        self.update(kwargs)
        self.magnification = 1.0 
Example 4
Project: Computable   Author: ktraunmueller   File: pyplot.py    License: MIT License 6 votes vote down vote up
def spy(Z, precision=0, marker=None, markersize=None, aspect='equal', hold=None, **kwargs):
    ax = gca()
    # allow callers to override the hold state by passing hold=True|False
    washold = ax.ishold()

    if hold is not None:
        ax.hold(hold)
    try:
        ret = ax.spy(Z, precision, marker, markersize, aspect, **kwargs)
        draw_if_interactive()
    finally:
        ax.hold(washold)
    if isinstance(ret, cm.ScalarMappable):
        sci(ret)
    return ret


################# REMAINING CONTENT GENERATED BY boilerplate.py ##############


# This function was autogenerated by boilerplate.py.  Do not edit as
# changes will be lost 
Example 5
Project: Computable   Author: ktraunmueller   File: colorbar.py    License: MIT License 6 votes vote down vote up
def colorbar(mappable, cax=None, ax=None, **kw):
    """
    Create a colorbar for a ScalarMappable instance.

    Documentation for the pylab thin wrapper:
    %(colorbar_doc)s
    """
    import matplotlib.pyplot as plt
    if ax is None:
        ax = plt.gca()
    if cax is None:
        cax, kw = make_axes(ax, **kw)
    cax.hold(True)
    cb = Colorbar(cax, mappable, **kw)

    def on_changed(m):
        cb.set_cmap(m.get_cmap())
        cb.set_clim(m.get_clim())
        cb.update_bruteforce(m)

    cbid = mappable.callbacksSM.connect('changed', on_changed)
    mappable.colorbar = cb
    ax.figure.sca(ax)
    return cb 
Example 6
Project: Computable   Author: ktraunmueller   File: colorbar.py    License: MIT License 6 votes vote down vote up
def colorbar(mappable, cax=None, ax=None, **kw):
    """
    Create a colorbar for a ScalarMappable instance.

    Documentation for the pylab thin wrapper:
    %(colorbar_doc)s
    """
    import matplotlib.pyplot as plt
    if ax is None:
        ax = plt.gca()
    if cax is None:
        cax, kw = make_axes(ax, **kw)
    cax.hold(True)
    cb = Colorbar(cax, mappable, **kw)

    def on_changed(m):
        cb.set_cmap(m.get_cmap())
        cb.set_clim(m.get_clim())
        cb.update_bruteforce(m)

    cbid = mappable.callbacksSM.connect('changed', on_changed)
    mappable.colorbar = cb
    ax.figure.sca(ax)
    return cb 
Example 7
Project: POT   Author: PythonOT   File: plot_barycenter_fgw.py    License: 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 8
Project: matplotlib-4-abaqus   Author: Solid-Mechanics   File: image.py    License: MIT License 6 votes vote down vote up
def __init__(self, fig,
                 cmap=None,
                 norm=None,
                 offsetx=0,
                 offsety=0,
                 origin=None,
                 **kwargs
                 ):

        """
        cmap is a colors.Colormap instance
        norm is a colors.Normalize instance to map luminance to 0-1

        kwargs are an optional list of Artist keyword args
        """
        martist.Artist.__init__(self)
        cm.ScalarMappable.__init__(self, norm, cmap)
        if origin is None:
            origin = rcParams['image.origin']
        self.origin = origin
        self.figure = fig
        self.ox = offsetx
        self.oy = offsety
        self.update(kwargs)
        self.magnification = 1.0 
Example 9
Project: matplotlib-4-abaqus   Author: Solid-Mechanics   File: pyplot.py    License: MIT License 6 votes vote down vote up
def spy(Z, precision=0, marker=None, markersize=None, aspect='equal', hold=None, **kwargs):
    ax = gca()
    # allow callers to override the hold state by passing hold=True|False
    washold = ax.ishold()

    if hold is not None:
        ax.hold(hold)
    try:
        ret = ax.spy(Z, precision, marker, markersize, aspect, **kwargs)
        draw_if_interactive()
    finally:
        ax.hold(washold)
    if isinstance(ret, cm.ScalarMappable):
        sci(ret)
    return ret


################# REMAINING CONTENT GENERATED BY boilerplate.py ##############


# This function was autogenerated by boilerplate.py.  Do not edit as
# changes will be lost 
Example 10
Project: matplotlib-4-abaqus   Author: Solid-Mechanics   File: colorbar.py    License: MIT License 6 votes vote down vote up
def colorbar(mappable, cax=None, ax=None, **kw):
    """
    Create a colorbar for a ScalarMappable instance.

    Documentation for the pylab thin wrapper:
    %(colorbar_doc)s
    """
    import matplotlib.pyplot as plt
    if ax is None:
        ax = plt.gca()
    if cax is None:
        cax, kw = make_axes(ax, **kw)
    cax.hold(True)
    cb = Colorbar(cax, mappable, **kw)

    def on_changed(m):
        cb.set_cmap(m.get_cmap())
        cb.set_clim(m.get_clim())
        cb.update_bruteforce(m)

    cbid = mappable.callbacksSM.connect('changed', on_changed)
    mappable.colorbar = cb
    ax.figure.sca(ax)
    return cb 
Example 11
Project: matplotlib-4-abaqus   Author: Solid-Mechanics   File: colorbar.py    License: MIT License 6 votes vote down vote up
def colorbar(mappable, cax=None, ax=None, **kw):
    """
    Create a colorbar for a ScalarMappable instance.

    Documentation for the pylab thin wrapper:
    %(colorbar_doc)s
    """
    import matplotlib.pyplot as plt
    if ax is None:
        ax = plt.gca()
    if cax is None:
        cax, kw = make_axes(ax, **kw)
    cax.hold(True)
    cb = Colorbar(cax, mappable, **kw)

    def on_changed(m):
        cb.set_cmap(m.get_cmap())
        cb.set_clim(m.get_clim())
        cb.update_bruteforce(m)

    cbid = mappable.callbacksSM.connect('changed', on_changed)
    mappable.colorbar = cb
    ax.figure.sca(ax)
    return cb 
Example 12
Project: neural-network-animation   Author: miloharper   File: image.py    License: MIT License 6 votes vote down vote up
def __init__(self, fig,
                 cmap=None,
                 norm=None,
                 offsetx=0,
                 offsety=0,
                 origin=None,
                 **kwargs
                 ):

        """
        cmap is a colors.Colormap instance
        norm is a colors.Normalize instance to map luminance to 0-1

        kwargs are an optional list of Artist keyword args
        """
        martist.Artist.__init__(self)
        cm.ScalarMappable.__init__(self, norm, cmap)
        if origin is None:
            origin = rcParams['image.origin']
        self.origin = origin
        self.figure = fig
        self.ox = offsetx
        self.oy = offsety
        self.update(kwargs)
        self.magnification = 1.0 
Example 13
Project: neural-network-animation   Author: miloharper   File: pyplot.py    License: MIT License 6 votes vote down vote up
def spy(Z, precision=0, marker=None, markersize=None, aspect='equal', hold=None, **kwargs):
    ax = gca()
    # allow callers to override the hold state by passing hold=True|False
    washold = ax.ishold()

    if hold is not None:
        ax.hold(hold)
    try:
        ret = ax.spy(Z, precision, marker, markersize, aspect, **kwargs)
        draw_if_interactive()
    finally:
        ax.hold(washold)
    if isinstance(ret, cm.ScalarMappable):
        sci(ret)
    return ret


################# REMAINING CONTENT GENERATED BY boilerplate.py ##############


# This function was autogenerated by boilerplate.py.  Do not edit as
# changes will be lost 
Example 14
Project: GraphicDesignPatternByPython   Author: Relph1119   File: contour.py    License: MIT License 6 votes vote down vote up
def changed(self):
        tcolors = [(tuple(rgba),)
                   for rgba in self.to_rgba(self.cvalues, alpha=self.alpha)]
        self.tcolors = tcolors
        hatches = self.hatches * len(tcolors)
        for color, hatch, collection in zip(tcolors, hatches,
                                            self.collections):
            if self.filled:
                collection.set_facecolor(color)
                # update the collection's hatch (may be None)
                collection.set_hatch(hatch)
            else:
                collection.set_color(color)
        for label, cv in zip(self.labelTexts, self.labelCValues):
            label.set_alpha(self.alpha)
            label.set_color(self.labelMappable.to_rgba(cv))
        # add label colors
        cm.ScalarMappable.changed(self) 
Example 15
Project: GraphicDesignPatternByPython   Author: Relph1119   File: colorbar.py    License: MIT License 6 votes vote down vote up
def colorbar(mappable, cax=None, ax=None, **kw):
    """
    Create a colorbar for a ScalarMappable instance.

    Documentation for the pyplot thin wrapper:

    %s
    """
    import matplotlib.pyplot as plt
    if ax is None:
        ax = plt.gca()
    if cax is None:
        cax, kw = make_axes(ax, **kw)
    cb = Colorbar(cax, mappable, **kw)

    def on_changed(m):
        cb.set_cmap(m.get_cmap())
        cb.set_clim(m.get_clim())
        cb.update_bruteforce(m)

    cbid = mappable.callbacksSM.connect('changed', on_changed)
    mappable.colorbar = cb
    ax.figure.sca(ax)
    return cb 
Example 16
Project: python3_ios   Author: holzschu   File: contour.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def changed(self):
        tcolors = [(tuple(rgba),)
                   for rgba in self.to_rgba(self.cvalues, alpha=self.alpha)]
        self.tcolors = tcolors
        hatches = self.hatches * len(tcolors)
        for color, hatch, collection in zip(tcolors, hatches,
                                            self.collections):
            if self.filled:
                collection.set_facecolor(color)
                # update the collection's hatch (may be None)
                collection.set_hatch(hatch)
            else:
                collection.set_color(color)
        for label, cv in zip(self.labelTexts, self.labelCValues):
            label.set_alpha(self.alpha)
            label.set_color(self.labelMappable.to_rgba(cv))
        # add label colors
        cm.ScalarMappable.changed(self) 
Example 17
Project: fenics-topopt   Author: zfergus   File: stress_gui.py    License: MIT License 5 votes vote down vote up
def __init__(self, nelx, nely, stress_calculator, nu, title=""):
        """Initialize plot and plot the initial design"""
        super(StressGUI, self).__init__(nelx, nely, title)
        self.stress_im = self.ax.imshow(
            np.swapaxes(np.zeros((nelx, nely, 4)), 0, 1),
            norm=colors.Normalize(vmin=0, vmax=1), cmap='jet')
        self.fig.colorbar(self.stress_im)
        self.stress_calculator = stress_calculator
        self.nu = nu
        self.myColorMap = colormaps.ScalarMappable(
            norm=colors.Normalize(vmin=0, vmax=1), cmap=colormaps.jet) 
Example 18
Project: fenics-topopt   Author: zfergus   File: stress_gui.py    License: MIT License 5 votes vote down vote up
def __init__(self, nelx, nely, stress_calculator, nu, title=""):
        """Initialize plot and plot the initial design"""
        super(StressGUI, self).__init__(nelx, nely, title)
        self.stress_im = self.ax.imshow(
            np.swapaxes(np.zeros((nelx, nely, 4)), 0, 1),
            norm=colors.Normalize(vmin=0, vmax=1), cmap='jet')
        self.fig.colorbar(self.stress_im)
        self.stress_calculator = stress_calculator
        self.nu = nu
        self.myColorMap = colormaps.ScalarMappable(
            norm=colors.Normalize(vmin=0, vmax=1), cmap=colormaps.jet) 
Example 19
Project: nmp_qc   Author: priba   File: Plotter.py    License: MIT License 5 votes vote down vote up
def plot_graph(self, am, position=None, cls=None, fig_name='graph.png'):

        with warnings.catch_warnings():
            warnings.filterwarnings("ignore")

            g = nx.from_numpy_matrix(am)

            if position is None:
                position=nx.drawing.circular_layout(g)

            fig = plt.figure()

            if cls is None:
                cls='r'
            else:
                # Make a user-defined colormap.
                cm1 = mcol.LinearSegmentedColormap.from_list("MyCmapName", ["r", "b"])

                # Make a normalizer that will map the time values from
                # [start_time,end_time+1] -> [0,1].
                cnorm = mcol.Normalize(vmin=0, vmax=1)

                # Turn these into an object that can be used to map time values to colors and
                # can be passed to plt.colorbar().
                cpick = cm.ScalarMappable(norm=cnorm, cmap=cm1)
                cpick.set_array([])
                cls = cpick.to_rgba(cls)
                plt.colorbar(cpick, ax=fig.add_subplot(111))


            nx.draw(g, pos=position, node_color=cls, ax=fig.add_subplot(111))

            fig.savefig(os.path.join(self.plotdir, fig_name)) 
Example 20
def _plot(self, a, key, title, gx, gy, num_x, num_y):
        pp.rcParams['figure.figsize'] = (
            self._image_width / 300, self._image_height / 300
        )
        pp.title(title)
        # Interpolate the data
        rbf = Rbf(
            a['x'], a['y'], a[key], function='linear'
        )
        z = rbf(gx, gy)
        z = z.reshape((num_y, num_x))
        # Render the interpolated data to the plot
        pp.axis('off')
        # begin color mapping
        norm = matplotlib.colors.Normalize(
            vmin=min(a[key]), vmax=max(a[key]), clip=True
        )
        mapper = cm.ScalarMappable(norm=norm, cmap='RdYlBu_r')
        # end color mapping
        image = pp.imshow(
            z,
            extent=(0, self._image_width, self._image_height, 0),
            cmap='RdYlBu_r', alpha=0.5, zorder=100
        )
        pp.colorbar(image)
        pp.imshow(self._layout, interpolation='bicubic', zorder=1, alpha=1)
        # begin plotting points
        for idx in range(0, len(a['x'])):
            pp.plot(
                a['x'][idx], a['y'][idx],
                marker='o', markeredgecolor='black', markeredgewidth=1,
                markerfacecolor=mapper.to_rgba(a[key][idx]), markersize=6
            )
        # end plotting points
        fname = '%s_%s.png' % (key, self._title)
        logger.info('Writing plot to: %s', fname)
        pp.savefig(fname, dpi=300)
        pp.close('all') 
Example 21
Project: LSDMappingTools   Author: LSDtopotools   File: colours.py    License: MIT License 5 votes vote down vote up
def colorbar_index(fig, cax, ncolors, cmap, drape_min_threshold, drape_max):
    """State-machine like function that creates a discrete colormap and plots
       it on a figure that is passed as an argument.

    Arguments:
       fig (matplotlib.Figure): Instance of a matplotlib figure object.
       cax (matplotlib.Axes): Axes instance to create the colourbar from.
           This must be the Axes containing the data that your colourbar will be
           mapped from.
       ncolors (int): The number of colours in the discrete colourbar map.
       cmap (str or Colormap object): Either the name of a matplotlib colormap, or
           an object instance of the colormap, e.g. cm.jet
       drape_min_threshold (float): Number setting the threshold level of the drape raster
           This should match any threshold you have set to mask the drape/overlay raster.
       drape_max (float): Similar to above, but for the upper threshold of your drape mask.
    """

    discrete_cmap = discrete_colourmap(ncolors, cmap)

    mappable = _cm.ScalarMappable(cmap=discrete_cmap)
    mappable.set_array([])
    #mappable.set_clim(-0.5, ncolors + 0.5)
    mappable.set_clim(drape_min_threshold, drape_max)

    print(type(fig))
    print(type(mappable))
    print(type(cax))
    print()
    cbar = _plt.colorbar(mappable, cax=cax) #switched from fig to plt to expose the labeling params
    print(type(cbar))
    #cbar.set_ticks(_np.linspace(0, ncolors, ncolors))
    pad = ((ncolors - 1) / ncolors) / 2  # Move labels to center of bars.
    cbar.set_ticks(_np.linspace(drape_min_threshold + pad, drape_max - pad,
                   ncolors))

    return cbar

# Generate random colormap 
Example 22
Project: dinosar   Author: scottyhq   File: __init__.py    License: MIT License 5 votes vote down vote up
def make_amplitude_cmap(
    mapname="gray", vmin=1, vmax=1e5, ncolors=64, outname="amplitude-cog.cpt"
):
    """Write default colormap (amplitude-cog.cpt) for isce amplitude images.

    Uses a LogNorm colormap by default since amplitude return values typically
    span several orders of magnitude.

    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)
    # NOTE for strong contrast amp return:
    # cNorm = colors.Normalize(vmin=1e3, vmax=1e4)
    cNorm = colors.LogNorm(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 23
Project: RVO_Py_MAS   Author: MengGuo   File: vis.py    License: GNU General Public License v2.0 5 votes vote down vote up
def get_cmap(N):
    '''Returns a function that maps each index in 0, 1, ... N-1 to a distinct RGB color.'''
    color_norm  = colors.Normalize(vmin=0, vmax=N-1)
    scalar_map = cmx.ScalarMappable(norm=color_norm, cmap='hsv') 
    def map_index_to_rgb_color(index):
        return scalar_map.to_rgba(index)
    return map_index_to_rgb_color 
Example 24
Project: ML-Recipes   Author: rougier   File: pca.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_cmap(N):
    '''Returns a function that maps each index in 0, 1, ... N-1 to a distinct
        RGB color.'''
    color_norm  = colors.Normalize(vmin=0, vmax=N)
    scalar_map = cmx.ScalarMappable(norm=color_norm, cmap='hsv')
    def map_index_to_rgb_color(index):
        return scalar_map.to_rgba(index)
    return map_index_to_rgb_color 
Example 25
Project: Computable   Author: ktraunmueller   File: image.py    License: MIT License 5 votes vote down vote up
def changed(self):
        """
        Call this whenever the mappable is changed so observers can
        update state
        """
        self._imcache = None
        self._rgbacache = None
        cm.ScalarMappable.changed(self) 
Example 26
Project: Computable   Author: ktraunmueller   File: image.py    License: MIT License 5 votes vote down vote up
def set_array(self, A):
        """
        Retained for backwards compatibility - use set_data instead

        ACCEPTS: numpy array A or PIL Image"""
        # This also needs to be here to override the inherited
        # cm.ScalarMappable.set_array method so it is not invoked
        # by mistake.

        self.set_data(A) 
Example 27
Project: Computable   Author: ktraunmueller   File: image.py    License: MIT License 5 votes vote down vote up
def set_cmap(self, cmap):
        if self._A is not None:
            raise RuntimeError('Cannot change colors after loading data')
        cm.ScalarMappable.set_cmap(self, cmap) 
Example 28
Project: Computable   Author: ktraunmueller   File: image.py    License: MIT License 5 votes vote down vote up
def __init__(self, ax,
                 x=None,
                 y=None,
                 A=None,
                 cmap=None,
                 norm=None,
                 **kwargs
                 ):
        """
        cmap defaults to its rc setting

        cmap is a colors.Colormap instance
        norm is a colors.Normalize instance to map luminance to 0-1

        Additional kwargs are matplotlib.artist properties

        """
        martist.Artist.__init__(self)
        cm.ScalarMappable.__init__(self, norm, cmap)
        self.axes = ax
        self._rgbacache = None
        # There is little point in caching the image itself because
        # it needs to be remade if the bbox or viewlim change,
        # so caching does help with zoom/pan/resize.
        self.update(kwargs)
        self.set_data(x, y, A) 
Example 29
Project: Computable   Author: ktraunmueller   File: image.py    License: MIT License 5 votes vote down vote up
def changed(self):
        self._rgbacache = None
        cm.ScalarMappable.changed(self) 
Example 30
Project: Computable   Author: ktraunmueller   File: image.py    License: MIT License 5 votes vote down vote up
def set_data(self, A):
        """Set the image array."""
        cm.ScalarMappable.set_array(self, cbook.safe_masked_invalid(A))