Python matplotlib.cm.ScalarMappable() Examples

The following are 30 code examples of matplotlib.cm.ScalarMappable(). 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.cm , 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: colorbar.py    From matplotlib-4-abaqus with 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 #3
Source File: image.py    From neural-network-animation with 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
Source File: pyplot.py    From Computable with 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
Source File: colorbar.py    From Computable with 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
Source File: colorbar.py    From Computable with 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
Source File: pyplot.py    From neural-network-animation with 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 #8
Source File: image.py    From Computable with 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
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 #10
Source File: contour.py    From GraphicDesignPatternByPython with 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 #11
Source File: colorbar.py    From GraphicDesignPatternByPython with 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 #12
Source File: __init__.py    From dinosar with 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 #13
Source File: colorbar.py    From matplotlib-4-abaqus with 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 #14
Source File: pyplot.py    From matplotlib-4-abaqus with 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 #15
Source File: contour.py    From python3_ios with 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 #16
Source File: image.py    From matplotlib-4-abaqus with 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 #17
Source File: image.py    From neural-network-animation with 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 #18
Source File: image.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, ax,
                 cmap=None,
                 norm=None,
                 interpolation=None,
                 origin=None,
                 filternorm=True,
                 filterrad=4.0,
                 resample=False,
                 **kwargs
                 ):
        """
        interpolation and cmap default to their rc settings

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

        extent is data axes (left, right, bottom, top) for making image plots
        registered with data plots.  Default is to label the pixel
        centers with the zero-based row and column indices.

        Additional kwargs are matplotlib.artist properties

        """
        martist.Artist.__init__(self)
        cm.ScalarMappable.__init__(self, norm, cmap)
        self._mouseover = True
        if origin is None:
            origin = rcParams['image.origin']
        self.origin = origin
        self.set_filternorm(filternorm)
        self.set_filterrad(filterrad)
        self.set_interpolation(interpolation)
        self.set_resample(resample)
        self.axes = ax

        self._imcache = None

        self.update(kwargs) 
Example #19
Source File: image.py    From neural-network-animation with 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 #20
Source File: image.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def set_array(self, A):
        """
        Retained for backwards compatibility - use set_data instead.

        Parameters
        ----------
        A : array-like
        """
        # 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 #21
Source File: image.py    From python3_ios with BSD 3-Clause "New" or "Revised" 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 #22
Source File: image.py    From python3_ios with BSD 3-Clause "New" or "Revised" 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, copy=True))
        self.stale = True 
Example #23
Source File: pyplot.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def spy(
        Z, precision=0, marker=None, markersize=None, aspect='equal',
        origin='upper', **kwargs):
    __ret = gca().spy(
        Z=Z, precision=precision, marker=marker,
        markersize=markersize, aspect=aspect, origin=origin, **kwargs)
    if isinstance(__ret, cm.ScalarMappable): sci(__ret)
    return __ret

# Autogenerated by boilerplate.py.  Do not edit as changes will be lost. 
Example #24
Source File: image.py    From neural-network-animation with 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 #25
Source File: image.py    From neural-network-animation with 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)) 
Example #26
Source File: utils.py    From cvml_project with MIT License 5 votes vote down vote up
def visualize_colormap(mat):
    # high_res_colormap
    vmax = np.percentile(mat, 95)
    normalizer = mpl.colors.Normalize(vmin=mat.min(), vmax=vmax)
    mapper = cm.ScalarMappable(norm=normalizer, cmap='magma')
    colormapped_im = (mapper.to_rgba(mat)[:, :, :3] * 255).astype(np.uint8)
    return colormapped_im


###########################################################################
# OS
########################################################################### 
Example #27
Source File: pyplot.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def gci():
    """
    Get the current colorable artist.  Specifically, returns the
    current :class:`~matplotlib.cm.ScalarMappable` instance (image or
    patch collection), or *None* if no images or patch collections
    have been defined.  The commands :func:`~matplotlib.pyplot.imshow`
    and :func:`~matplotlib.pyplot.figimage` create
    :class:`~matplotlib.image.Image` instances, and the commands
    :func:`~matplotlib.pyplot.pcolor` and
    :func:`~matplotlib.pyplot.scatter` create
    :class:`~matplotlib.collections.Collection` instances.  The
    current image is an attribute of the current axes, or the nearest
    earlier axes in the current figure that contains an image.
    """
    return gcf()._gci() 
Example #28
Source File: pyplot.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def rcdefaults():
    matplotlib.rcdefaults()
    draw_if_interactive()


# The current "image" (ScalarMappable) is retrieved or set
# only via the pyplot interface using the following two
# functions: 
Example #29
Source File: image.py    From matplotlib-4-abaqus with 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)) 
Example #30
Source File: image.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def changed(self):
        self._rgbacache = None
        cm.ScalarMappable.changed(self)