當前位置: 首頁>>代碼示例>>Python>>正文


Python cm.ScalarMappable方法代碼示例

本文整理匯總了Python中matplotlib.cm.ScalarMappable方法的典型用法代碼示例。如果您正苦於以下問題:Python cm.ScalarMappable方法的具體用法?Python cm.ScalarMappable怎麽用?Python cm.ScalarMappable使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在matplotlib.cm的用法示例。


在下文中一共展示了cm.ScalarMappable方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: __init__

# 需要導入模塊: from matplotlib import cm [as 別名]
# 或者: from matplotlib.cm import ScalarMappable [as 別名]
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 
開發者ID:ktraunmueller,項目名稱:Computable,代碼行數:27,代碼來源:image.py

示例2: write_cmap

# 需要導入模塊: from matplotlib import cm [as 別名]
# 或者: from matplotlib.cm import ScalarMappable [as 別名]
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 
開發者ID:scottyhq,項目名稱:dinosar,代碼行數:27,代碼來源:__init__.py

示例3: make_coherence_cmap

# 需要導入模塊: from matplotlib import cm [as 別名]
# 或者: from matplotlib.cm import ScalarMappable [as 別名]
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 
開發者ID:scottyhq,項目名稱:dinosar,代碼行數:27,代碼來源:__init__.py

示例4: spy

# 需要導入模塊: from matplotlib import cm [as 別名]
# 或者: from matplotlib.cm import ScalarMappable [as 別名]
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 
開發者ID:ktraunmueller,項目名稱:Computable,代碼行數:24,代碼來源:pyplot.py

示例5: colorbar

# 需要導入模塊: from matplotlib import cm [as 別名]
# 或者: from matplotlib.cm import ScalarMappable [as 別名]
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 
開發者ID:ktraunmueller,項目名稱:Computable,代碼行數:26,代碼來源:colorbar.py

示例6: graph_colors

# 需要導入模塊: from matplotlib import cm [as 別名]
# 或者: from matplotlib.cm import ScalarMappable [as 別名]
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. 
開發者ID:PythonOT,項目名稱:POT,代碼行數:21,代碼來源:plot_barycenter_fgw.py

示例7: changed

# 需要導入模塊: from matplotlib import cm [as 別名]
# 或者: from matplotlib.cm import ScalarMappable [as 別名]
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) 
開發者ID:Relph1119,項目名稱:GraphicDesignPatternByPython,代碼行數:20,代碼來源:contour.py

示例8: colorbar

# 需要導入模塊: from matplotlib import cm [as 別名]
# 或者: from matplotlib.cm import ScalarMappable [as 別名]
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 
開發者ID:Relph1119,項目名稱:GraphicDesignPatternByPython,代碼行數:26,代碼來源:colorbar.py

示例9: __init__

# 需要導入模塊: from matplotlib import cm [as 別名]
# 或者: from matplotlib.cm import ScalarMappable [as 別名]
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) 
開發者ID:zfergus,項目名稱:fenics-topopt,代碼行數:13,代碼來源:stress_gui.py

示例10: plot_graph

# 需要導入模塊: from matplotlib import cm [as 別名]
# 或者: from matplotlib.cm import ScalarMappable [as 別名]
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)) 
開發者ID:priba,項目名稱:nmp_qc,代碼行數:35,代碼來源:Plotter.py

示例11: _plot

# 需要導入模塊: from matplotlib import cm [as 別名]
# 或者: from matplotlib.cm import ScalarMappable [as 別名]
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') 
開發者ID:jantman,項目名稱:python-wifi-survey-heatmap,代碼行數:40,代碼來源:heatmap.py

示例12: colorbar_index

# 需要導入模塊: from matplotlib import cm [as 別名]
# 或者: from matplotlib.cm import ScalarMappable [as 別名]
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 
開發者ID:LSDtopotools,項目名稱:LSDMappingTools,代碼行數:40,代碼來源:colours.py

示例13: make_amplitude_cmap

# 需要導入模塊: from matplotlib import cm [as 別名]
# 或者: from matplotlib.cm import ScalarMappable [as 別名]
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 
開發者ID:scottyhq,項目名稱:dinosar,代碼行數:31,代碼來源:__init__.py

示例14: get_cmap

# 需要導入模塊: from matplotlib import cm [as 別名]
# 或者: from matplotlib.cm import ScalarMappable [as 別名]
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 
開發者ID:MengGuo,項目名稱:RVO_Py_MAS,代碼行數:9,代碼來源:vis.py

示例15: get_cmap

# 需要導入模塊: from matplotlib import cm [as 別名]
# 或者: from matplotlib.cm import ScalarMappable [as 別名]
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 
開發者ID:rougier,項目名稱:ML-Recipes,代碼行數:10,代碼來源:pca.py


注:本文中的matplotlib.cm.ScalarMappable方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。