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


Python ScalarMappable.set_clim方法代码示例

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


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

示例1: _create_colorbar

# 需要导入模块: from matplotlib.cm import ScalarMappable [as 别名]
# 或者: from matplotlib.cm.ScalarMappable import set_clim [as 别名]
 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,代码行数:12,代码来源:seattle_choropleth.py

示例2: plot_net_layerwise

# 需要导入模块: from matplotlib.cm import ScalarMappable [as 别名]
# 或者: from matplotlib.cm.ScalarMappable import set_clim [as 别名]
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,代码行数:56,代码来源:visualize.py

示例3: custom_colorbar

# 需要导入模块: from matplotlib.cm import ScalarMappable [as 别名]
# 或者: from matplotlib.cm.ScalarMappable import set_clim [as 别名]
def custom_colorbar(cmap, ncolors, breaks, **kwargs):
    from matplotlib.colors import BoundaryNorm
    from matplotlib.cm import ScalarMappable
    import matplotlib.colors as mplc

    breaklabels = ['No Counts']+["> %d counts"%(perc) for perc in breaks[:-1]]

    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(breaklabels)
    return colorbar
开发者ID:RaySSharma,项目名称:crime-activity-seattle,代码行数:18,代码来源:choropleth.py

示例4: custom_colorbar

# 需要导入模块: from matplotlib.cm import ScalarMappable [as 别名]
# 或者: from matplotlib.cm.ScalarMappable import set_clim [as 别名]
def custom_colorbar(cmap, ncolors, labels, **kwargs):    
    """Create a custom, discretized colorbar with correctly formatted/aligned labels.
    
    cmap: the matplotlib colormap object you plan on using for your graph
    ncolors: (int) the number of discrete colors available
    labels: the list of labels for the colorbar. Should be the same length as ncolors.
    """
    from matplotlib.colors import BoundaryNorm
    from matplotlib.cm import ScalarMappable
        
    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:tylerhartley,项目名称:personal,代码行数:21,代码来源:latitude-blogcopy.py

示例5: make_plot

# 需要导入模块: from matplotlib.cm import ScalarMappable [as 别名]
# 或者: from matplotlib.cm.ScalarMappable import set_clim [as 别名]
  def make_plot(self, val, cct, clm,
                cmap = 'jet', cmap_norm = None,
                cmap_vmin = None, cmap_vmax = None):

    # make color mapping
    smap = ScalarMappable(cmap_norm, cmap)
    smap.set_clim(cmap_vmin, cmap_vmax)
    smap.set_array(val)
    bin_colors = smap.to_rgba(val)

    # make patches
    patches = []
    for i_c, i_clm in enumerate(clm):
      patches.append(Rectangle((i_clm[0],  i_clm[2]),
                                i_clm[1] - i_clm[0],
                                i_clm[3] - i_clm[2]))
    patches_colle = PatchCollection(patches)
    patches_colle.set_edgecolor('face')
    patches_colle.set_facecolor(bin_colors)

    return patches_colle, smap
开发者ID:shiaki,项目名称:astro-viskit,代码行数:23,代码来源:adapt_hist.py

示例6: _custom_colorbar

# 需要导入模块: from matplotlib.cm import ScalarMappable [as 别名]
# 或者: from matplotlib.cm.ScalarMappable import set_clim [as 别名]
def _custom_colorbar(cmap, ncolors, labels, **kwargs):
        """Create a custom, discretized colorbar with correctly formatted/aligned labels.
        It was inspired mostly by the example provided in http://beneathdata.com/how-to/visualizing-my-location-history/

        :param cmap: the matplotlib colormap object you plan on using for your graph
        :param ncolors: (int) the number of discrete colors available
        :param labels: the list of labels for the colorbar. Should be the same length as ncolors.

        :return: custom colorbar
        """

        if ncolors <> len(labels):
            raise MapperError("Number of colors is not compatible with the number of labels")
        else:
            norm = BoundaryNorm(range(0, ncolors), cmap.N)
            mappable = ScalarMappable(cmap=cmap)
            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:ds-ga-1007,项目名称:final_project,代码行数:25,代码来源:Mapper_utils.py

示例7: make_cmap_sm_norm

# 需要导入模块: from matplotlib.cm import ScalarMappable [as 别名]
# 或者: from matplotlib.cm.ScalarMappable import set_clim [as 别名]
def make_cmap_sm_norm(d=None,clim=None,cmap=None):
	if cmap == 'red_blue':
		cmap = red_blue_cm()
	if cmap == 'banas_cm':
		if clim==None:
			cmap = banas_cm(np.min(d[:]),np.min(d[:]),np.max(d[:]),np.max(d[:]))
		elif len(clim) == 2:
			cmap = banas_cm(clim[0],clim[0],clim[1],clim[1])
		elif len(clim) == 4:
			cmap = banas_cm(clim[0],clim[1],clim[2],clim[3])
	elif cmap == 'banas_hsv_cm':
		if clim==None:
			cmap = banas_hsv_cm(np.min(d[:]),np.min(d[:]),np.max(d[:]),np.max(d[:]))
		elif len(clim) == 2:
			cmap = banas_hsv_cm(clim[0],clim[0],clim[1],clim[1])
		elif len(clim) == 4:
			cmap = banas_hsv_cm(clim[0],clim[1],clim[2],clim[3])
	
	norm = Normalize(vmin=clim[0],vmax=clim[-1],clip=False)
	sm = ScalarMappable(norm=norm,cmap=cmap)
	sm.set_clim(vmin=clim[0],vmax=clim[-1])
	sm.set_array(np.array([0]))

	return cmap,sm,norm
开发者ID:HyeonJeongKim,项目名称:tools,代码行数:26,代码来源:plot_utils.py

示例8: PCA_sklearn

# 需要导入模块: from matplotlib.cm import ScalarMappable [as 别名]
# 或者: from matplotlib.cm.ScalarMappable import set_clim [as 别名]
# for location in locations['features']:
# 	print location

locations = locations["features"][20:22]

pca = PCA_sklearn()
pca.fit(predictors, locations, startdate=startdate, enddate=enddate)
# pca.save('pca.nc')
# pca.load('pca.nc')
reduced_predictors = pca.transform(predictors, startdate=startdate, enddate=enddate)

vmin = 0
vmax = 50
mappable = ScalarMappable(cmap="Blues")
mappable.set_array(np.arange(vmin, vmax, 0.1))
mappable.set_clim((vmin, vmax))

id = 20
for pred in reduced_predictors:

    tree = BinaryTree(pred, maxdepth=10)

    fig = plt.fig = plt.figure(figsize=(10, 10))
    ax = fig.add_subplot(111)
    # 	ax.scatter(np.array(tree.samples)[:,0], np.array(tree.samples)[:,1], s=1, alpha=0.4, color='black')
    values = np.ma.masked_less(predictand_data[:, id], 0.1)
    # 	ax.scatter(np.array(tree.samples)[:,0], np.array(tree.samples)[:,1], c='grey', s=5, alpha=0.3)
    # 	ax.scatter(np.array(tree.samples)[:,0], np.array(tree.samples)[:,1], c=values, s=values, alpha=0.7)
    tree.plot_density(ax, mappable)
    plt.show()
开发者ID:jackaranda,项目名称:phasespace,代码行数:32,代码来源:run_tree.py

示例9: style_all_tags

# 需要导入模块: from matplotlib.cm import ScalarMappable [as 别名]
# 或者: from matplotlib.cm.ScalarMappable import set_clim [as 别名]
def style_all_tags(soup, container, background=True, margin=None, border=False, css=True, images=True, only_container=False):
    """Only used for debugging"""

    #if only_container:
        #soup = container

    (min_score, max_score) = get_min_and_max_scores(soup)
    min_score = -log(-min_score)
    max_score = log(max_score)

    sm = ScalarMappable(cmap=RdYlGn)
    sm.set_clim(0,1)

    if not css:
        for link in soup.find_all("link"):
            link.decompose()

    if not images:
        for img in soup.find_all("img"):
            img.decompose()

    for tag in soup.find_all():

        if not isinstance(tag, element.Tag):
            continue

        if css:
            try:
                style = tag["style"].split(";")
            except:
                style = []
        else:
            style = []

        if margin is not None:
            if margin > 0:
                style.append("margin: %dpx" % margin)

        try:
            score = sum(tag.scores.values())
            rgb = score_to_rgb(score, sm, min_score, max_score)
            tag.scores['total'] = score
        except:
            score = -1
            rgb = (230, 230, 230)

        if background:
            style.append("background-color: rgb(%d,%d,%d)" % rgb)

        try:
            if tag in container.descendants and score > -30:
                style.append("color: #000000")
            else:
                style.append("color: #666666")
        except:
            pass

        if tag == container:
            style.append("border: 3px dashed #0000CC")
            style.append("color: #000000")
        else:
            if border:
                style.append("border: 1px solid #333333")

        try:
            tag['style'] = "; ".join(style)
            tag['scores'] = repr(tag.scores)
            del tag.scores['total']
        except:
            pass
开发者ID:jdevalk,项目名称:reporter,代码行数:72,代码来源:core.py

示例10: SpiroGraph

# 需要导入模块: from matplotlib.cm import ScalarMappable [as 别名]
# 或者: from matplotlib.cm.ScalarMappable import set_clim [as 别名]
class SpiroGraph(object):

    '''
    Spirograph drawer with matplotlib slider widgets to change parameters.
    Parameters of line are:

        R: The radius of the big circle
        r: The radius of the small circle which rolls along the inside of the
           bigger circle
        p: distance from centre of smaller circle to point in the circle where
           the pen hole is.
        tmax: the angle through which the smaller circle is rotated to draw the
              spirograph
        tstep: how often matplotlib plots a point
        a, b, c: parameters of the linewidth equation.
    '''

    # kwargs for each of the matplotlib sliders
    slider_kwargs = (
        {'label': 't_max', 'valmin': np.pi, 'valmax': 200 * np.pi,
         'valinit': tmax0, 'valfmt': PiString()},
        {'label': 't_step', 'valmin': 0.01,
         'valmax': 10, 'valinit': tstep0},
        {'label': 'R', 'valmin': 1, 'valmax': 200, 'valinit': R0},
        {'label': 'r', 'valmin': 1, 'valmax': 200, 'valinit': r0},
        {'label': 'p', 'valmin': 1, 'valmax': 200, 'valinit': p0},
        {'label': 'colour', 'valmin': 0, 'valmax': 1, 'valinit': 1},
        {'label': 'width_a', 'valmin': 0.5, 'valmax': 10, 'valinit': 1},
        {'label': 'width_b', 'valmin': 0, 'valmax': 10, 'valinit': 0},
        {'label': 'width_c', 'valmin': 0, 'valmax': 10, 'valinit': 0.5})

    rbutton_kwargs = (
        {'labels': ('black', 'white'), 'activecolor': 'white', 'active': 0},
        {'labels': ('solid', 'variable'), 'activecolor': 'white', 'active': 0})

    def __init__(self, colormap, figsize=(7, 10)):
        self.colormap_name = colormap
        self.variable_color = False
        # Use ScalarMappable to map full colormap to range 0 - 1
        self.colormap = ScalarMappable(cmap=colormap)
        self.colormap.set_clim(0, 1)

        # set up main axis onto which to draw spirograph
        self.figsize = figsize
        plt.rcParams['figure.figsize'] = figsize
        self.fig, self.mainax = plt.subplots()
        plt.subplots_adjust(bottom=0.3)
        title = self.mainax.set_title('Spirograph Drawer!',
                                      size=20,
                                      color='white')
        self.text = [title, ]
        # set up slider axes
        self.slider_axes = [plt.axes([0.25, x, 0.65, 0.015])
                            for x in np.arange(0.05, 0.275, 0.025)]
        # same again for radio buttons
        self.rbutton_axes = [plt.axes([0.025, x, 0.1, 0.15])
                             for x in np.arange(0.02, 0.302, 0.15)]
        # use log scale for tstep slider
        self.slider_axes[1].set_xscale('log')
        # turn off frame, ticks and tick labels for all axes
        for ax in chain(self.slider_axes, self.rbutton_axes, [self.mainax, ]):
            ax.axis('off')
        # use axes and kwargs to create list of sliders/rbuttons
        self.sliders = [Slider(ax, **kwargs)
                        for ax, kwargs in zip(self.slider_axes,
                                              self.slider_kwargs)]
        self.rbuttons = [RadioButtons(ax, **kwargs)
                         for ax, kwargs in zip(self.rbutton_axes,
                                               self.rbutton_kwargs)]
        self.update_figcolors()

        # set up initial line
        self.t = np.arange(0, tmax0, tstep0)
        x, y = spiro_linefunc(self.t, R0, r0, p0)
        self.linecollection = LineCollection(
            segments(x, y),
            linewidths=spiro_linewidths(self.t, a0, b0, c0),
            color=self.colormap.to_rgba(col0))
        self.mainax.add_collection(self.linecollection)

        # creates the plot and connects sliders to various update functions
        self.run()

    def update_figcolors(self, bgcolor='black'):
        '''
        function run by background color radiobutton. Sets all labels, text,
        and sliders to foreground color, all axes to background color
        '''
        fgcolor = 'white' if bgcolor == 'black' else 'black'
        self.fig.set_facecolor(bgcolor)
        self.mainax.set_axis_bgcolor(bgcolor)
        for ax in chain(self.slider_axes, self.rbutton_axes):
            ax.set_axis_bgcolor(bgcolor)

        # set fgcolor elements to black or white, mostly elements of sliders
        for item in chain(map(attrgetter('label'), self.sliders),
                          map(attrgetter('valtext'), self.sliders),
                          map(attrgetter('poly'), self.sliders),
                          self.text,
                          *map(attrgetter('labels'), self.rbuttons)):
#.........这里部分代码省略.........
开发者ID:mparker2,项目名称:spirograph,代码行数:103,代码来源:spirograph.py


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