当前位置: 首页>>代码示例>>Python>>正文


Python ScalarMappable.to_rgba方法代码示例

本文整理汇总了Python中matplotlib.cm.ScalarMappable.to_rgba方法的典型用法代码示例。如果您正苦于以下问题:Python ScalarMappable.to_rgba方法的具体用法?Python ScalarMappable.to_rgba怎么用?Python ScalarMappable.to_rgba使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在matplotlib.cm.ScalarMappable的用法示例。


在下文中一共展示了ScalarMappable.to_rgba方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: digit_to_rgb

# 需要导入模块: from matplotlib.cm import ScalarMappable [as 别名]
# 或者: from matplotlib.cm.ScalarMappable import to_rgba [as 别名]
def digit_to_rgb(X, scaling=3, shape = (), cmap = 'binary'):
    '''
    Takes as input an intensity array and produces a rgb image due to some color map

    Parameters
    ----------

    X : numpy.ndarray
        intensity matrix as array of shape [M x N]

    scaling : int
        optional. positive integer value > 0

    shape: tuple or list of its , length = 2
        optional. if not given, X is reshaped to be square.

    cmap : str
        name of color map of choice. default is 'binary'

    Returns
    -------

    image : numpy.ndarray
        three-dimensional array of shape [scaling*H x scaling*W x 3] , where H*W == M*N
    '''

    sm = ScalarMappable(cmap = cmap)
    image = sm.to_rgba(enlarge_image(vec2im(X,shape), scaling))[:,:,0:3]
    return image
开发者ID:Scitator,项目名称:lrp_toolbox,代码行数:31,代码来源:render.py

示例2: create_heatmap

# 需要导入模块: from matplotlib.cm import ScalarMappable [as 别名]
# 或者: from matplotlib.cm.ScalarMappable import to_rgba [as 别名]
def create_heatmap(xs, ys, imageSize, blobSize, cmap):
    blob = Image.new('RGBA', (blobSize * 2, blobSize * 2), '#000000')
    blob.putalpha(0)
    colour = 255 / int(math.sqrt(len(xs)))
    draw = ImageDraw.Draw(blob)
    draw.ellipse((blobSize / 2, blobSize / 2, blobSize * 1.5, blobSize * 1.5),
                 fill=(colour, colour, colour))
    blob = blob.filter(ImageFilter.GaussianBlur(radius=blobSize / 2))
    heat = Image.new('RGBA', (imageSize, imageSize), '#000000')
    heat.putalpha(0)
    xScale = float(imageSize - 1) / (max(xs) - min(xs))
    yScale = float(imageSize - 1) / (min(ys) - max(ys))
    xOff = min(xs)
    yOff = max(ys)
    for i in range(len(xs)):
        xPos = int((xs[i] - xOff) * xScale)
        yPos = int((ys[i] - yOff) * yScale)
        blobLoc = Image.new('RGBA', (imageSize, imageSize), '#000000')
        blobLoc.putalpha(0)
        blobLoc.paste(blob, (xPos - blobSize, yPos - blobSize), blob)
        heat = ImageChops.add(heat, blobLoc)

    norm = Normalize(vmin=min(min(heat.getdata())),
                     vmax=max(max(heat.getdata())))
    sm = ScalarMappable(norm, cmap)
    heatArray = pil_to_array(heat)
    rgba = sm.to_rgba(heatArray[:, :, 0], bytes=True)
    rgba[:, :, 3] = heatArray[:, :, 3]
    coloured = Image.fromarray(rgba, 'RGBA')

    return coloured
开发者ID:PatMart,项目名称:RTLSDR-Scanner,代码行数:33,代码来源:utils_mpl.py

示例3: make_graph

# 需要导入模块: from matplotlib.cm import ScalarMappable [as 别名]
# 或者: from matplotlib.cm.ScalarMappable import to_rgba [as 别名]
def make_graph(data):
	from matplotlib.cm import jet, ScalarMappable
	from matplotlib.colors import Normalize
	g = nx.Graph()
	cnorm = Normalize(vmin=1, vmax=241)
	smap = ScalarMappable(norm=cnorm, cmap=jet)
	edge_list = []
	for k in data:
		tk = k.split('_')
		if len(tk) != 5:
			g.add_node(k)
		else:
			a,b = tk[1],tk[3]
			g.add_node(a)
			g.add_node(b)
			g.add_edge(a,b)
	pos = nx.spring_layout(g)
	nxcols,glabels = [],{}
	for i,node in enumerate(g.nodes()):
		if '_' not in node:
			nxcols.append(smap.to_rgba(int(node)))
		else:
			nxcols.append((0,1,0,0))
	nx.draw_networkx_nodes(g,pos,node_color=nxcols)
	nx.draw_networkx_labels(g,pos)
	nx.draw_networkx_edges(g,pos)
	plt.show()
	return 
开发者ID:dmcskim,项目名称:act_inact,代码行数:30,代码来源:second_look.py

示例4: get_color_map

# 需要导入模块: from matplotlib.cm import ScalarMappable [as 别名]
# 或者: from matplotlib.cm.ScalarMappable import to_rgba [as 别名]
 def get_color_map(self, levels):
     """Returns gradient of color from green to red.
     """
     sm = ScalarMappable(cmap='RdYlGn_r')
     normed_levels = levels / np.max(levels)
     colors = 255 * sm.to_rgba(normed_levels)[:, :3]
     return ['#%02x%02x%02x' % (r, g, b) for r,g,b in colors]
开发者ID:Nathx,项目名称:pdf_mapping_berlin,代码行数:9,代码来源:mapper.py

示例5: scatter3d

# 需要导入模块: from matplotlib.cm import ScalarMappable [as 别名]
# 或者: from matplotlib.cm.ScalarMappable import to_rgba [as 别名]
def scatter3d(x,y,z, cs, colorsMap='jet'):
    cm = plt.get_cmap(colorsMap)
    cNorm = Normalize(vmin=min(cs), vmax=max(cs))
    scalarMap = ScalarMappable(norm=cNorm, cmap=cm)
    ax.scatter(x, y, z, c=scalarMap.to_rgba(cs), s=5, linewidth=0)
    scalarMap.set_array(cs)
    plt.show()
开发者ID:hermitdemschoenenleben,项目名称:muenster,代码行数:9,代码来源:caustic_pos.py

示例6: getcolor

# 需要导入模块: from matplotlib.cm import ScalarMappable [as 别名]
# 或者: from matplotlib.cm.ScalarMappable import to_rgba [as 别名]
 def getcolor(self, V, F):
     dS = numpy.empty(len(F))
     for i, f in enumerate(F):
         v = V[f][0]
         dS[i] = v[0] * v[0] + v[1] * v[1] + v[2] * v[2]
     cmap = ScalarMappable(cmap='jet')
     cmap.set_array(dS)
     return cmap, cmap.to_rgba(dS)
开发者ID:jianmingtang,项目名称:PIC-tools,代码行数:10,代码来源:mplFig.py

示例7: _check_cmap_rgb_vals

# 需要导入模块: from matplotlib.cm import ScalarMappable [as 别名]
# 或者: from matplotlib.cm.ScalarMappable import to_rgba [as 别名]
def _check_cmap_rgb_vals(vals, cmap, vmin=0, vmax=1):
    """Helper function to check RGB values of color images"""
    from matplotlib.colors import Normalize
    from matplotlib.cm import ScalarMappable
    norm = Normalize(vmin, vmax)
    sm = ScalarMappable(norm=norm, cmap=cmap)
    for val, rgb_expected in vals:
        rgb_actual = sm.to_rgba(val)[:-1]
        assert_allclose(rgb_actual, rgb_expected, atol=1e-5)
开发者ID:cdeil,项目名称:gammapy,代码行数:11,代码来源:test_plotting.py

示例8: plot_events

# 需要导入模块: from matplotlib.cm import ScalarMappable [as 别名]
# 或者: from matplotlib.cm.ScalarMappable import to_rgba [as 别名]
def plot_events(mapobj,axisobj,catalog,label= None, color='depth', pretty = False, colormap=None, 
             llat = -90, ulat = 90, llon = -180, ulon = 180, figsize=(16,24), 
             par_range = (-90., 120., 30.), mer_range = (0., 360., 60.),
             showHour = False, M_above = 0.0, location = 'World', min_size=1, max_size=8,**kwargs):

    '''Simplified version of plot_event'''

    import matplotlib.pyplot as plt
    from matplotlib.colors import Normalize
    from matplotlib.cm import ScalarMappable

    lats, lons, mags, times, labels, colors = get_event_info(catalog, M_above, llat, ulat, llon, ulon, color, label)
                    
    min_color = min(colors)
    max_color = max(colors)

    if colormap is None:
        if color == "date":
             colormap = plt.get_cmap()
        else:
            # Choose green->yellow->red for the depth encoding.
             colormap = plt.get_cmap("RdYlGn_r")
                
    scal_map = ScalarMappable(norm=Normalize(min_color, max_color),
                                  cmap=colormap)
    scal_map.set_array(np.linspace(0, 1, 1))

    x, y = mapobj(lons, lats)

    min_mag = 0
    max_mag = 10
    if len(mags) > 1:
        frac = [(_i - min_mag) / (max_mag - min_mag) for _i in mags]
        magnitude_size = [(_i * (max_size - min_size)) ** 2 for _i in frac]
        #magnitude_size = [(_i * min_size) for _i in mags]
        #print magnitude_size
        colors_plot = [scal_map.to_rgba(c) for c in colors]
    else:
        magnitude_size = 15.0 ** 2
        colors_plot = "red"

    quakes = mapobj.scatter(x, y, marker='o', s=magnitude_size, c=colors_plot, zorder=10)
    #mapobj.drawmapboundary(fill_color='aqua')
    #mapobj.drawparallels(np.arange(-90,90,30),labels=[1,0,0,0])
    #mapobj.drawmeridians(np.arange(mapobj.lonmin,mapobj.lonmax+30,60),labels=[0,0,0,1])

    # if len(mags) > 1:
    #     cb = mpl.colorbar.ColorbarBase(ax=axisobj, cmap=colormap, orientation='vertical')
    #     cb.set_ticks([0, 0.25, 0.5, 0.75, 1.0])
    #     color_range = max_color - min_color
    #     cb.set_ticklabels([_i.strftime('%Y-%b-%d') if color == "date" else '%.1fkm' % (_i)
    #             for _i in [min_color, min_color + color_range * 0.25,
    #                    min_color + color_range * 0.50,
    #                    min_color + color_range * 0.75, max_color]])

    return quakes
开发者ID:rmartinshort,项目名称:Interactive_MT,代码行数:58,代码来源:cat_analysis.py

示例9: cm2colors

# 需要导入模块: from matplotlib.cm import ScalarMappable [as 别名]
# 或者: from matplotlib.cm.ScalarMappable import to_rgba [as 别名]
def cm2colors(N, cmap='autumn'):
    """Takes N evenly spaced colors out of cmap and returns a
    list of rgb values"""
    values = range(N)
    cNorm  = Normalize(vmin=0, vmax=N-1)
    scalarMap = ScalarMappable(norm=cNorm, cmap=cmap)
    colors = []
    for i in xrange(N):
        colors.append(scalarMap.to_rgba(values[i]))
    return colors
开发者ID:Captain-Sandwich,项目名称:compphys,代码行数:12,代码来源:util.py

示例10: plotTciData

# 需要导入模块: from matplotlib.cm import ScalarMappable [as 别名]
# 或者: from matplotlib.cm.ScalarMappable import to_rgba [as 别名]
    def plotTciData(self, ax):
        rdata = self.elecTree.getNode('\electrons::top.tci.results:rad').data()
        sm = ScalarMappable()
        rhoColor = sm.to_rgba(-rdata)

        for i in range(1,11):
            pnode = self.elecTree.getNode('\electrons::top.tci.results:nl_%02d' % i)
            ax.plot(pnode.dim_of().data(), pnode.data(), c = rhoColor[i-1])

        ax.set_ylabel('ne')
开发者ID:Maplenormandy,项目名称:psfc-misc,代码行数:12,代码来源:tempMap.py

示例11: _update_scatter

# 需要导入模块: from matplotlib.cm import ScalarMappable [as 别名]
# 或者: from matplotlib.cm.ScalarMappable import to_rgba [as 别名]
  def _update_scatter(self):
    # Updates the scatter points for changes in *tidx* or *xidx*. This 
    # just changes the face color
    # 
    # CALL THIS AFTER *_update_image*
    #
    if len(self.data_sets) < 2:
      return

    sm = ScalarMappable(norm=self.cbar.norm,cmap=self.cbar.get_cmap())
    colors = sm.to_rgba(self.data_sets[1][self.tidx,:,2])
    self.scatter.set_facecolors(colors)
开发者ID:treverhines,项目名称:PyGeoNS,代码行数:14,代码来源:ivector.py

示例12: ColorMapper

# 需要导入模块: from matplotlib.cm import ScalarMappable [as 别名]
# 或者: from matplotlib.cm.ScalarMappable import to_rgba [as 别名]
class ColorMapper(object):
    def __init__(self, bottom_val, top_val, color_palette_name):
        cnorm = mpl_Normalize(vmin=bottom_val, vmax=top_val)
        comap = get_cmap(color_palette_name)
        self.scalar_map = ScalarMappable(norm=cnorm, cmap=comap)

    @staticmethod
    def rgb_to_hex(rgb):
        res = tuple([int(c * 255) for c in rgb])
        return '#%02x%02x%02x' % res

    def color_from_val(self, val):
        return self.rgb_to_hex(self.scalar_map.to_rgba(val)[:3])
开发者ID:bsherin,项目名称:tactic,代码行数:15,代码来源:matplotlib_utilities.py

示例13: plot_res

# 需要导入模块: from matplotlib.cm import ScalarMappable [as 别名]
# 或者: from matplotlib.cm.ScalarMappable import to_rgba [as 别名]
    def plot_res(self, ax, do_label=True, tag_leafs=False, zlim=False,
                 cmap='jet_r'):

        from matplotlib.pyplot import get_cmap
        from matplotlib import patheffects
        from matplotlib.colors import LogNorm
        from matplotlib.cm import ScalarMappable
        
        # Create a color map using either zlim as given or max/min resolution.
        cNorm = LogNorm(vmin=self.dx_min, vmax=self.dx_max, clip=True)
        cMap  = ScalarMappable(cmap=get_cmap(cmap), norm=cNorm)
            
        dx_vals = {}
        
        for key in self.tree:
            if self[key].isLeaf:
                color = cMap.to_rgba(self[key].dx)
                dx_vals[self[key].dx] = 1.0
                #if self[key].dx in res_colors:
                #    dx_vals[self[key].dx] = 1.0
                #    color=#res_colors[self[key].dx]
                #else:
                #    color='k'
                self[key].plot_res(ax, fc=color, label=key*tag_leafs)

        if do_label:
            
            ax.annotate('Resolution:', [1.02,0.99], xycoords='axes fraction', 
                        color='k',size='medium')
            for i,key in enumerate(sorted(dx_vals.keys())):
                #dx_int = log2(key)
                if key<1:
                    label = '1/%i' % (key**-1)
                else:
                    label = '%i' % key
                ax.annotate('%s $R_{E}$'%label, [1.02,0.87-i*0.1],
                            xycoords='axes fraction', color=cMap.to_rgba(key),
                            size='x-large',path_effects=[patheffects.withStroke(
                                linewidth=1,foreground='k')])
开发者ID:spacepy,项目名称:spacepy,代码行数:41,代码来源:qotree.py

示例14: generalized_bar_chart

# 需要导入模块: from matplotlib.cm import ScalarMappable [as 别名]
# 或者: from matplotlib.cm.ScalarMappable import to_rgba [as 别名]
def generalized_bar_chart(code_matrix, trans_names, code_names, show_it=True, show_trans_names=False, color_map = "jet", legend_labels = None, title=None, horizontal_grid = True):
    ldata = {}
    fig = pylab.figure(facecolor="white", figsize=(12, 4))
    fig.subplots_adjust(left=.05, bottom=.15, right=.98, top=.95)
    code_names = [c for c in range(code_matrix.shape[1])]
    for i, code in enumerate(range(len(code_names))):
        ldata[code] = [code_matrix[j, i] for j in range(len(trans_names))]
    ind = np.arange(len(trans_names))
    width = 1.0 / (len(code_names) + 1)
    traditional_colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple', 'black', 'grey', 'cyan', 'coral']

    ax = fig.add_subplot(111)
    if title is not None:
        ax.set_title(title, fontsize=10)

    if color_map == "AA_traditional_":
        lcolors = traditional_colors
    else:
        cNorm = mpl_Normalize(vmin = 1, vmax = len(code_names))
        comap = get_cmap(color_map)
        scalar_map = ScalarMappable(norm = cNorm, cmap = comap)
        lcolors = [scalar_map.to_rgba(idx + 1) for idx in range(len(code_names))]

    the_bars = []

    for c in range(len(code_names)):
        new_bars = ax.bar(ind + (c + .5) * width, ldata[code_names[c]], width, color=lcolors[c % (len(lcolors))])
        the_bars.append(new_bars[0])
        # bar_groups.append(bars)
    if show_trans_names:
        ax.set_xticks(ind + .5)
        ax.set_xticklabels(trans_names, size="x-small", rotation= -45)
    else:
        ax.grid(b = horizontal_grid, which = "major", axis = 'y')
        ax.set_xticks(ind + .5)
        ax.set_xticklabels(ind + 1, size="x-small")
        for i in ind[1:]:
            ax.axvline(x = i, linestyle = "--", linewidth = .25, color = 'black')

    if legend_labels != None:
        fontP =FontProperties()
        fontP.set_size('small')
        box = ax.get_position()
        ax.set_position([box.x0, box.y0, box.width * 0.825, box.height])
        # Put a legend to the right of the current axis
        ax.legend(the_bars, legend_labels, loc='center left', bbox_to_anchor=(1, 0.5), prop = fontP)
    ax.set_xlim(right=len(trans_names))

    if show_it:
        fig.show()
    return fig
开发者ID:bsherin,项目名称:shared_tools,代码行数:53,代码来源:matplotlib_window.py

示例15: plot

# 需要导入模块: from matplotlib.cm import ScalarMappable [as 别名]
# 或者: from matplotlib.cm.ScalarMappable import to_rgba [as 别名]
def plot(countries,values,label='',clim=None,verbose=False):
    """
    Usage: worldmap.plot(countries, values [, label] [, clim])
    """
    countries_shp = shpreader.natural_earth(resolution='110m',category='cultural',
                                            name='admin_0_countries')
    ## Create a plot
    fig = plt.figure()
    ax = plt.axes(projection=ccrs.PlateCarree())
    ## Create a colormap
    cmap = plt.get_cmap('RdYlGn_r')
    if clim:
       vmin = clim[0]
       vmax = clim[1]
    else:
       val = values[np.isfinite(values)]
       mean = val.mean()
       std = val.std()
       vmin = mean-2*std
       vmax = mean+2*std
    norm = Normalize(vmin=vmin,vmax=vmax)
    smap = ScalarMappable(norm=norm,cmap=cmap)
    ax2 = fig.add_axes([0.3, 0.18, 0.4, 0.03])
    cbar = ColorbarBase(ax2,cmap=cmap,norm=norm,orientation='horizontal')
    cbar.set_label(label)
    ## Add countries to the map
    for country in shpreader.Reader(countries_shp).records():
        countrycode = country.attributes['adm0_a3']
        countryname = country.attributes['name_long']
        ## Check for country code consistency
        if countrycode == 'SDS': #South Sudan
           countrycode = 'SSD'
        elif countrycode == 'ROU': #Romania
           countrycode = 'ROM'
        elif countrycode == 'COD': #Dem. Rep. Congo
           countrycode = 'ZAR'
        elif countrycode == 'KOS': #Kosovo
           countrycode = 'KSV'
        if countrycode in countries:
           val = values[countries==countrycode]
           if np.isfinite(val):
              color = smap.to_rgba(val)
           else:
              color = 'grey'
        else:
           color = 'w'
           if verbose:
              print("No data available for "+countrycode+": "+countryname)
        ax.add_geometries(country.geometry,ccrs.PlateCarree(),facecolor=color,label=countryname)
    plt.show()
开发者ID:andflopezbec,项目名称:Python,代码行数:52,代码来源:worldmap.py


注:本文中的matplotlib.cm.ScalarMappable.to_rgba方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。