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


Python cm.ScalarMappable类代码示例

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


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

示例1: ColorbarWidget

class ColorbarWidget(QWidget):

    def __init__(self, parent=None):
        super(ColorbarWidget, self).__init__(parent)
        fig = Figure()
        rect = 0.25, 0.05, 0.1, 0.90
        self.cb_axes = fig.add_axes(rect)
        self.canvas = FigureCanvas(fig)
        self.setLayout(QVBoxLayout())
        self.layout().addWidget(self.canvas)
        self.button = QPushButton("Update")
        self.layout().addWidget(self.button)
        self.button.pressed.connect(self._update_cb_scale)

        self._create_colorbar(fig)

    def _create_colorbar(self, fig):
        self.mappable = ScalarMappable(norm=SymLogNorm(0.0001, 1,vmin=-10., vmax=10000.),
                                  cmap=DEFAULT_CMAP)
        self.mappable.set_array([])
        fig.colorbar(self.mappable, ax=self.cb_axes, cax=self.cb_axes)

    def _update_cb_scale(self):
        self.mappable.colorbar.remove()
        rect = 0.25, 0.05, 0.1, 0.90
        self.cb_axes = self.canvas.figure.add_axes(rect)
        self.mappable = ScalarMappable(Normalize(30, 4300),
                                   cmap=DEFAULT_CMAP)
        self.mappable.set_array([])
        self.canvas.figure.colorbar(self.mappable, ax=self.cb_axes, cax=self.cb_axes)
        self.canvas.draw()
开发者ID:martyngigg,项目名称:sandbox,代码行数:31,代码来源:cbar.py

示例2: scatter3d

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,代码行数:7,代码来源:caustic_pos.py

示例3: create_heatmap

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,代码行数:31,代码来源:utils_mpl.py

示例4: get_color_map

 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,代码行数:7,代码来源:mapper.py

示例5: make_graph

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,代码行数:28,代码来源:second_look.py

示例6: digit_to_rgb

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,代码行数:29,代码来源:render.py

示例7: getcolor

 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,代码行数:8,代码来源:mplFig.py

示例8: _check_cmap_rgb_vals

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,代码行数:9,代码来源:test_plotting.py

示例9: plot_events

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,代码行数:56,代码来源:cat_analysis.py

示例10: _create_colorbar

 def _create_colorbar(self, cmap, ncolors, labels, **kwargs):    
     norm = BoundaryNorm(range(0, ncolors), cmap.N)
     mappable = ScalarMappable(cmap=cmap, norm=norm)
     mappable.set_array([])
     mappable.set_clim(-0.5, ncolors+0.5)
     colorbar = plt.colorbar(mappable, **kwargs)
     colorbar.set_ticks(np.linspace(0, ncolors, ncolors+1)+0.5)
     colorbar.set_ticklabels(range(0, ncolors))
     colorbar.set_ticklabels(labels)
     return colorbar
开发者ID:hendrikTpl,项目名称:SEA_traffic_accident_prediction,代码行数:10,代码来源:seattle_choropleth.py

示例11: plotTciData

    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,代码行数:10,代码来源:tempMap.py

示例12: cm2colors

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,代码行数:10,代码来源:util.py

示例13: plot_net_layerwise

def plot_net_layerwise(net, x_spacing=5, y_spacing=10, colors=[], use_labels=True, ax=None, cmap='gist_heat', cbar=False, positions={}):
	if not colors:
		colors = [1] * net.size()
	args = {
		'ax' : ax,
		'node_color' : colors,
		'nodelist' : net.nodes(), # ensure that same order is used throughout for parallel data like colors
		'vmin' : 0,
		'vmax' : 1,
		'cmap' : cmap
	}

	if not positions:
		# compute layer-wise positions of nodes (distance from roots)
		nodes_by_layer = defaultdict(lambda: [])
		def add_to_layer(n,l):
			nodes_by_layer[l].append(n)
		net.bfs_traverse(net.get_roots(), add_to_layer)


		positions = {}
		for l, nodes in nodes_by_layer.iteritems():
			y = -l*y_spacing
			# reorder layer lexicographically
			nodes.sort(key=lambda n: n.get_name())
			width = (len(nodes)-1) * x_spacing
			for i,n in enumerate(nodes):
				x = x_spacing*i - width/2
				positions[n] = (x,y)
	args['pos'] = positions

	if use_labels:
		labels = {n:n.get_name() for n in net.iter_nodes()}
		args['labels'] = labels

	if ax is None:
		ax = plt.figure().add_subplot(1,1,1)
	nxg = net_to_digraph(net)
	nx.draw_networkx(nxg, **args)
	ax.tick_params(axis='x', which='both', bottom='off', top='off', labelbottom='off')
	ax.tick_params(axis='y', which='both', left='off', right='off', labelleft='off')
	
	if cbar:
		color_map = ScalarMappable(cmap=cmap)
		color_map.set_clim(vmin=0, vmax=1)
		color_map.set_array(np.array([0,1]))
		plt.colorbar(color_map, ax=ax)

	ax.set_aspect('equal')
	# zoom out slightly to avoid cropping issues with nodes
	xl = ax.get_xlim()
	yl = ax.get_ylim()
	ax.set_xlim(xl[0]-x_spacing/2, xl[1]+x_spacing/2)
	ax.set_ylim(yl[0]-y_spacing/2, yl[1]+y_spacing/2)
开发者ID:wrongu,项目名称:sampling-dynamics,代码行数:54,代码来源:visualize.py

示例14: _update_scatter

  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,代码行数:12,代码来源:ivector.py

示例15: densityplot2

    def densityplot2(self,modelname='Model',refname='Ref',units = 'mmol m-3',sub = 'med'):
        '''
        opectool like density plot
        
        Ref is in x axis
        Model  in y axis
        
        Args
         - *modelname* (optional) string , default ='Model'
         - *refname*   (optional) string , default ='Ref'
         - *units*     (optional) string , default ='mmol m-3'
         - *sub*       (optional) string , default ='med'
        
        
        Returns: a matplotlib Figure object and a matplotlib Axes object
        '''
        
        fig, ax = plt.subplots()
        plt.title('%s Density plot of %s and %s\nNumber of considered matchups: %s' % (sub, modelname, refname, self.number()))
        cmap = 'spectral_r'
        axis_min = min(self.Ref.min(),self.Model.min())
        axis_max = max(self.Ref.max(),self.Model.max())
        extent = [axis_min, axis_max, axis_min, axis_max]

        hexbin = ax.hexbin(self.Ref, self.Model, bins=None, extent=extent, cmap=cmap)
        data = hexbin.get_array().astype(np.int32)
        MAX = data.max()

        for nticks in range(10,2,-1):
            float_array=np.linspace(0,MAX,nticks)
            int___array = float_array.astype(np.int32)
            if np.all(float_array == int___array ):
                break

        mappable = ScalarMappable(cmap=cmap)
        mappable.set_array(data)
        #fig.colorbar(mappable, ticks = int___array, ax=ax)
        cbar = fig.colorbar(mappable, ax=ax)
        labels = cbar.ax.get_yticklabels()
        FloatNumberFlag = False
        for label in labels:
            numstr = str(label.get_text())
            if numstr.find(".") > -1:
                FloatNumberFlag = True

        if FloatNumberFlag:
            cbar.remove()
            cbar = fig.colorbar(mappable, ticks = int___array, ax=ax)

        ax.set_xlabel('%s %s' % (refname,  units))
        ax.set_ylabel('%s %s' % (modelname,units))
        ax.grid()
        return fig,ax
开发者ID:inogs,项目名称:bit.sea,代码行数:53,代码来源:statistics.py


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