• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python pylab.get_cmap函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: plot_sun_image

def plot_sun_image(img, filename, wavelength, title = '', vmin=0.0, vmax = 1.0):
    if wavelength == 'hmi':
        cmap = plt.get_cmap('hmimag')
    else:
        cmap = plt.get_cmap('sdoaia{}'.format(wavelength))
    plt.title(title)
    plt.imshow(img,cmap=cmap,origin='lower',vmin=vmin, vmax=vmax)
    plt.savefig(filename)
    plt.close("all")
开发者ID:Yukorin5,项目名称:pythonscript,代码行数:9,代码来源:observational_data.py


示例2: __init__

    def __init__(self,name):
        self.name=name
        self.log=False
        self.filter=lambda x:x
        self.vmin=None
        self.vmax=None
        self._norm=None
        self.compression=6
        self.set_depth(8)

        m=CM_RE.match(name)
        if m!=None:
            LOG.debug("%s -> %s",name,repr(m.groups()))
            cmap,min_val,max_val,under_color,over_color,bad_color=m.groups()
            if cmap.endswith('-log'):
                self.filter=np.log10
                self.log=True
                cmap=cmap[:-4]
            self.cmap=get_cmap(cmap)

            if min_val and max_val: 
                self.set_minmax(float(min_val),float(max_val))

            if under_color: self.cmap.set_under('#'+under_color[:6],alpha=int(under_color[6:],16)/255.0 if under_color[6:] else 1.0)
            if over_color: self.cmap.set_over('#'+over_color[:6],alpha=int(over_color[6:],16)/255.0 if over_color[6:] else 1.0)
            if bad_color: self.cmap.set_bad('#'+bad_color[:6],alpha=int(bad_color[6:],16)/255.0 if bad_color[6:] else 1.0)

        try:
            from PIL import Image
            self.Image=Image
            self._write=self._write_pil
            LOG.debug('Using PIL for image writing')
        except ImportError:
            self._write=self._write_png
            LOG.debug('Using PNG for image writing')
开发者ID:geodynamics-liberation-front,项目名称:wallander,代码行数:35,代码来源:viz.py


示例3: over_plot_googlemap

    def over_plot_googlemap(self):
 
        import folium
        from folium import plugins
        import matplotlib.colors as colors
        import matplotlib.cm as cmx

        colorMap = plt.get_cmap('cool')
        cNorm = colors.Normalize(vmin=1920, vmax=1990)
        scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=colorMap)

        x = self.dic_nodes['x']; y = self.dic_nodes['y'] 
        Lead = 10**np.array( self.dic_nodes['value'] ) - 1.
        Year = self._generate_new_value(tag='Year Built')

        map = folium.Map(location=[43.0125, -83.6875], zoom_start=13)

        for i in range(len(x)):       
            colorVal = scalarMap.to_rgba(Year[i])
            colorVal = colors.rgb2hex(colorVal)
            radius = 40*np.sqrt(Lead[i])
            disc = 'Expected Lead : %i\n'%Lead[i] +\
                   'Expected Year : %i\n'%Year[i]
            folium.CircleMarker([y[i], x[i]], radius=radius,
                       popup=disc, color=None,
                       fill_color=colorVal).add_to(map)

        map.create_map(path='prediction.html')        
开发者ID:AZaitzeff,项目名称:flint-water,代码行数:28,代码来源:networkPredictionPipeline.py


示例4: plot_runs

def plot_runs(runs):
    """ Plot population evolutions
    """
    ts = range(len(runs[0]))
    cmap = plt.get_cmap('viridis')
    for i, r in enumerate(runs):
        mean, var = zip(*r)
        bm, cm = zip(*mean)
        bv, cv = zip(*var)

        color = cmap(float(i)/len(runs))

        plt.errorbar(ts, bm, fmt='-', yerr=bv, c=color)
        plt.errorbar(ts, cm, fmt='--', yerr=cv, c=color)

    plt.title('population evolution overview')
    plt.xlabel('time')
    plt.ylabel('value')

    plt.ylim((0, 1))

    plt.plot(0, 0, '-', c='black', label='benefit value')
    plt.plot(0, 0, '--', c='black', label='cost value')
    plt.legend(loc='best')

    plt.savefig('result.pdf')
    plt.show()
开发者ID:kpj,项目名称:PySpaMo,代码行数:27,代码来源:evolutionary_optimization.py


示例5: ShowSlice

def ShowSlice(vals, min_val, max_val):
	import matplotlib.pyplot as plt

	# tell imshow about color map so that only set colors are used
	img = plt.imshow(vals,cmap = plt.get_cmap('gray'),vmin=min_val, vmax=max_val)

	plt.show()
开发者ID:davidbrough1,项目名称:CSE-6730-Project-2,代码行数:7,代码来源:MKS.py


示例6: colorize

def colorize(vector,cmap='plasma', vmin=None, vmax=None):
    """Convert a vector to RGBA colors.

    Parameters
    ----------
    vector : array
        Array of values to be represented by relative colors     
    cmap : str (optional)
        Matplotlib Colormap name
    vmin : float (optional)
        Minimum value for color normalization. Defaults to np.min(vector)
    vmax : float (optional)
        Maximum value for color normalization. Defaults to np.max(vector)
        
    Returns
    -------
    vcolors : np.ndarray
        Array of RGBA colors
    scalarmap : matplotlib.cm.ScalarMappable
        ScalerMap to convert values to colors
    cNorm : matplotlib.colors.Normalize
        Color normalization
    """
    
    if vmin is None: vmin = np.min(vector)
    if vmax is None: vmax = np.max(vector)    
    
    cm = plt.get_cmap(cmap)
    cNorm  = colors.Normalize(vmin=vmin, vmax=vmax)
    scalarmap = cmx.ScalarMappable(norm=cNorm, cmap=cm)
    vcolors = scalarmap.to_rgba(vector)
    
    return vcolors,scalarmap,cNorm
开发者ID:jlustigy,项目名称:jakely,代码行数:33,代码来源:colorize.py


示例7: simulate_sequence

def simulate_sequence(D, L, iterations, min_size, max_size, step_size, loop_avoid, reflect):

    poly = Polymer(D, L, loop_avoid, reflect=reflect)
    data = []

    for N in range(min_size,max_size, step_size):
        print N #Poor's man progress bar
        data_per_N = []
        bad_number = 0
        for i in range(iterations):
            (last, count, grid) = poly.create_polymer(N)
            dist = linalg.norm(last - poly.start_point)
            #print [dist,count,N]
            df = pd.DataFrame({"dist":[dist], "N": [N], "count" : [count]})
            data.append(df)

            #Save some example realization.
            if i == 10 and D == 2:
                pylab.figure()
                pylab.imshow(grid, cmap=pylab.get_cmap("binary"), interpolation="none")
                pylab.savefig("realization_N=%d_self_avoid=%d" % (N, loop_avoid))

        bad_ratio = 1.0*bad_number/iterations
        if bad_ratio > 0.02:
            print "To many bads with N=%d. Bad ratio %.3f" % (N, bad_ratio)


        #draw_distribution(D,L,N,iterations,loop_avoid, data_per_N)


        #R2 = (data_per_N**2).mean()
        #data.append((R2, N))

    data = pd.concat(data)
    return data
开发者ID:ronenabr,项目名称:polymer_constractor,代码行数:35,代码来源:main.py


示例8: plot

def plot(lon, lat, var1, var2, actions, ax, fig, **kwargs):
    aspect = kwargs.get('aspect', None)
    height = kwargs.get('height')
    width = kwargs.get('width')
    norm = kwargs.get('norm')
    cmap = get_cmap(kwargs.get('cmap', 'jet'))
    cmin = kwargs.get('cmin', "None")
    cmax = kwargs.get('cmax', "None")
    magnitude = kwargs.get('magnitude', 'False')
    if var1 is not None:
        if var2 is not None:
            mag = np.sqrt(var1**2 + var2**2)
        else:
            if magnitude == 'False':
                mag = var1
            else:
                mag = np.abs(var1)
        mag = mag.squeeze()
        if "pcolor" in actions:
            fig.set_figheight(height/80.0)
            fig.set_figwidth(width/80.0)
            pcolor(lon, lat, mag, ax, cmin, cmax, cmap)
        if "facets" in actions:
            fig.set_figheight(height/80.0)
            fig.set_figwidth(width/80.0)
            pcolor(lon, lat, mag, ax, cmin, cmax, cmap)
        elif "filledcontours" in actions:
            fig.set_figheight(height/80.0)
            fig.set_figwidth(width/80.0)
            fcontour(lon, lat, mag, ax, norm, cmin, cmax, cmap)
        elif "contours" in actions:
            fig.set_figheight(height/80.0)
            fig.set_figwidth(width/80.0)
            contour(lon, lat, mag, ax, norm, cmin, cmax, cmap)
        #elif "facets" in actions:
        #    fig.set_figheight(height/80.0)
        #    fig.set_figwidth(width/80.0)
        #    facet(lon, lat, mag, ax)
        elif "vectors" in actions:
            fig.set_figheight(height/80.0/aspect)
            fig.set_figwidth(width/80.0)
            vectors(lon, lat, var1, var2, mag, ax, norm, cmap, magnitude)
        elif "unitvectors" in actions:
            fig.set_figheight(height/80.0/aspect)
            fig.set_figwidth(width/80.0)
            unit_vectors(lon, lat, var1, var2, mag, ax, norm, cmap, magnitude)
        elif "streamlines" in actions:
            fig.set_figheight(height/80.0/aspect)
            fig.set_figwidth(width/80.0)
            m = kwargs.get('basemap')
            lonmin = kwargs.get("lonmin")
            latmin = kwargs.get("latmin")
            lonmax = kwargs.get("lonmax")
            latmax = kwargs.get("latmax")
            streamlines(lon, lat, var1, var2, mag, ax, norm, cmap, magnitude, m, lonmin, latmin, lonmax, latmax)
        elif "barbs" in actions:
            fig.set_figheight(height/80.0/aspect)
            fig.set_figwidth(width/80.0)
            barbs(lon, lat, var1, var2, mag, ax, norm, cmin, cmax, cmap, magnitude)
开发者ID:dstuebe,项目名称:sci-wms,代码行数:59,代码来源:cgrid.py


示例9: plotConfiguration

def plotConfiguration(conf):
    
    cmap = plt.get_cmap('viridis')
    fig, ax = plt.subplots()
    for i in range(0,conf.orbitals):
        ax.plot(conf.configurations[0:conf.beads,i,1],range(0,conf.beads),"o",color=cmap(i*1./conf.orbitals));
        
    return {"fig":fig,"ax":ax}
开发者ID:lucaparisi91,项目名称:qmc,代码行数:8,代码来源:anal.py


示例10: plotIntensity

def plotIntensity(data): #plots intensity in color map
  plot = data.sumPols().getData()
  if len(plot.shape) != 2: #check if waterfall file is valid
      sys.exit("Waterplot may only plot waterfall files")
  vmin, vmax = vlim(plot) #get color scale
      
  if isinstance(data, Data.SpecData):
      t_all = data.getTrange()
      f_all = data.getFrange()
      plt.imshow(plot.T, aspect='auto', interpolation='nearest', 
             origin='lower', cmap=plt.get_cmap('Greys'), 
             extent= t_all + f_all, vmin=vmin, vmax=vmax)
  elif isinstance(data, Data.Data):
      plt.imshow(plot.T, aspect='auto', interpolation='nearest', 
             origin='lower', cmap=plt.get_cmap('Greys'), 
             vmin=vmin, vmax=vmax)
  plt.show()
开发者ID:niyuan1,项目名称:psrplt,代码行数:17,代码来源:waterplot.py


示例11: plot_sun_image

def plot_sun_image(img, filename, wavelength=193, title = ''):
    #cmap = plt.get_cmap('sdoaia{}'.format(wavelength))
    cmap = plt.get_cmap('sohoeit195')
    plt.title(title)
    cax = plt.imshow(img,cmap=cmap,origin='lower',vmin=0, vmax=3000)#,vmin=vmin, vmax=vmax)
    plt.gcf().colorbar(cax)
    plt.savefig(filename)
    plt.close("all")
开发者ID:Yukorin5,项目名称:pythonscript,代码行数:8,代码来源:test-eit-plot.py


示例12: group_causality

def group_causality(sig_list, condition, freqs, ROI_labels=None,
                    out_path=None, submount=10):

    """
    Make group causality analysis, by evaluating significant matrices across
    subjects.
    ----------
    sig_list: list
        The path list of individual significant causal matrix.
    condition: string
        One condition of the experiments.
    freqs: list
        The list of interest frequency band.
    min_subject: string
        The subject for the common brain space.
    submount: int
        Significant interactions come out at least in 'submount' subjects.
    """
    print 'Running group causality...'
    set_directory(out_path)
    sig_caus = []

    for f in sig_list:
        sig_cau = np.load(f)
        print sig_cau.shape[-1]
        sig_caus.append(sig_cau)

    sig_caus = np.array(sig_caus)
    sig_group = sig_caus.sum(axis=0)
    plt.close()
    for i in xrange(len(sig_group)):
        fmin, fmax = freqs[i][0], freqs[i][1]
        cau_band = sig_group[i]
        # cau_band[cau_band < submount] = 0
        cau_band[cau_band < submount] = 0
        # fig, ax = pl.subplots()
        cmap = plt.get_cmap('hot', cau_band.max()+1-submount)
        cmap.set_under('gray')
        plt.matshow(cau_band, interpolation='nearest', vmin=submount, cmap=cmap)
        if ROI_labels == None:
            ROI_labels = np.arange(cau_band.shape[0]) + 1
        pl.xticks(np.arange(cau_band.shape[0]), ROI_labels, fontsize=9, rotation='vertical')
        pl.yticks(np.arange(cau_band.shape[0]), ROI_labels, fontsize=9)
        # pl.imshow(cau_band, interpolation='nearest')
        # pl.set_cmap('BlueRedAlpha')
        np.save(out_path + '/%s_%s_%sHz.npy' %
                (condition, str(fmin), str(fmax)), cau_band)
        v = np.arange(submount, cau_band.max()+1, 1)

        # cax = ax.scatter(x, y, c=z, s=100, cmap=cmap, vmin=10, vmax=z.max())
        # fig.colorbar(extend='min')

        plt.colorbar(ticks=v, extend='min')
        # pl.show()
        plt.savefig(out_path + '/%s_%s_%sHz.png' %
                    (condition, str(fmin), str(fmax)), dpi=300)
        plt.close()
    return
开发者ID:dongqunxi,项目名称:jumeg,代码行数:58,代码来源:apply_causality_whole.py


示例13: colors

def colors(numcolors,map='spectral'):
    std_col = ['r','b','g','m']
    if numcolors <= 4:
        return std_col[:numcolors]
    cm=plt.get_cmap(map)
    col = []
    for i in range(numcolors):
        col.append(cm(1.*i/numcolors))
    return col
开发者ID:pyIPP,项目名称:trgui,代码行数:9,代码来源:fconf.py


示例14: color_by_prop

def color_by_prop(propArr, nbins):
	colorArr = []
	for icl in xrange(nbins):
		colorArr.append(plt.get_cmap("hsv")(float(icl)/(nbins)))

	color_id_Arr = N.zeros_like(propArr)
	#propbins = N.logspace(N.log10(colorprops*0.99), N.log10(colorprops*1.01), ncolor+1)
	p_ids, p_bins = pTdf.group_by_prop(propArr, takelog=True, fixed_interval=True, bins=[])
	return p_ids, p_bins, colorArr
开发者ID:ynoh,项目名称:highz_dwarfs,代码行数:9,代码来源:plot_mJVSmG.py


示例15: showGraph

def showGraph(graph):
    G_adj = adjacencyList(np.array(graph))
    G = nx.DiGraph(G_adj)
    # nx.write_adjlist(G_adj, )
    #initialze Figure
    pos = nx.spring_layout(G)
    nx.draw_networkx_nodes(G, pos, cmap=plt.get_cmap('jet'))
    nx.draw_networkx_edges(G, pos,  edge_color='b', arrows=True)
    plt.show()
开发者ID:sad-,项目名称:sojvalasseha,代码行数:9,代码来源:visualize.py


示例16: plot_matrix

def plot_matrix(matrix):
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.set_title("colorMap")
    vmax = np.max(np.max(matrix), -1 * np.min(matrix))
    plt.imshow(matrix, interpolation="none", cmap=plt.get_cmap("seismic"), vmin=-1 * vmax, vmax=vmax)
    ax.set_aspect("equal")
    plt.colorbar(orientation="vertical")
    plt.show()
开发者ID:iampritishpatil,项目名称:CAMP_codes,代码行数:9,代码来源:functions.py


示例17: __init__

    def __init__(self,vmin=None,vmax=None,
                 filter=lambda x:x, 
                 depth=8,compression=None,
                 colormap=plt.get_cmap('jet'),
                 over_color=None, over_alpha=1.0,
                 under_color=None, under_alpha=1.0,
                 bad_color=None, bad_alpha=1.0,
                 gamma=1.0):
        self.filter=filter

        if vmin!=None and vmax!=None:
            self.set_minmax(float(vmin),float(vmax))
        else:
            self.vmin=None
            self.vmax=None
            self._norm=None
        if compression!=None:
            compression=int(compression)
        self.compression=compression

        self.set_depth(int(depth))

        if isinstance(colormap,str):
            self.colormap=plt.get_cmap(colormap)
        else:
            self.colormap=colormap
        if over_color!=None:
            try:
                int(over_color,16)
                over_color='#'+over_color
            except ValueError:
                pass
            self.colormap.set_over(over_color,alpha=float(over_alpha))
        if under_color!=None:
            try:
                int(under_color,16)
                under_color='#'+under_color
            except ValueError:
                pass
            self.colormap.set_under(under_color,alpha=float(under_alpha))
        if bad_color!=None:
            self.colormap.set_bad(bad_color,alpha=float(bad_alpha))
        self.colormap.set_gamma(float(gamma))
开发者ID:the-life-tectonic,项目名称:stagpypy,代码行数:43,代码来源:viz.py


示例18: _plot_colormap

 def _plot_colormap(self,cm):
     r=Renderer(colormap=plt.get_cmap(cm))
     name=os.path.join(self.dir,cm+"_h.png")
     if not os.path.exists(name):
         f=open(name,'wb')
         r.write_h_colorbar(f)
         f.close()
     name=os.path.join(self.dir,cm+"_v.png")
     if not os.path.exists(name):
         f=open(name,'wb')
         r.write_v_colorbar(f)
         f.close()
开发者ID:the-life-tectonic,项目名称:stagpypy,代码行数:12,代码来源:viz.py


示例19: plot_2d

def plot_2d(params_dir):
    model_dirs = [name for name in os.listdir(params_dir)
                  if os.path.isdir(os.path.join(params_dir, name))]
    if len(model_dirs) == 0:
      model_dirs = [params_dir]


    colors = plt.get_cmap('plasma')
    plt.figure(figsize=(20, 10))
    ax = plt.subplot(111)
    ax.set_xlabel('Learning Rate')
    ax.set_ylabel('Error rate')

    i = 0
    for model_dir in model_dirs:
        model_df = pd.DataFrame()
        for param_path in glob.glob(os.path.join(params_dir,
                                                 model_dir) + '/*.h5'):
            param = dd.io.load(param_path)
            gd = {'learning rate': param['hyperparameters']['learning_rate'],
                  'momentum': param['hyperparameters']['momentum'],
                  'dropout': param['hyperparameters']['dropout'],
                  'val. objective': param['best_epoch']['validate_objective']}
            model_df = model_df.append(pd.DataFrame(gd, index=[0]),
                                       ignore_index=True)
        if i != len(model_dirs) - 1:
            ax.scatter(model_df['learning rate'],
                       model_df['val. objective'],
                       s=128,
                       marker=(i+3, 0),
                       edgecolor='black',
                       linewidth=model_df['dropout'],
                       label=model_dir,
                       c=model_df['momentum'],
                       cmap=colors)
        else:
            im = ax.scatter(model_df['learning rate'],
                            model_df['val. objective'],
                            s=128,
                            marker=(i+3, 0),
                            edgecolor='black',
                            linewidth=model_df['dropout'],
                            label=model_dir,
                            c=model_df['momentum'],
                            cmap=colors)
        i += 1

    plt.colorbar(im, label='Momentum')
    plt.legend()
    plt.show()
    plt.savefig('{}.eps'.format(os.path.join(IMAGES_DIRECTORY, 'params2d')), format='eps', dpi=1000)
    plt.close()
开发者ID:rafaelvalle,项目名称:MDI,代码行数:52,代码来源:plot_parameters_tried.py


示例20: visualize

def visualize(y_true,y_pred,img):

    score = accuracy_score(y_true, y_pred)
    print '\n accuracy score : ', score

    h, w = img.shape
    target_pred = y_pred.reshape(h, w)
    target_true = y_true.reshape(h, w)

    fig1 = plt.figure(1)
    plt.imshow(img, cmap=plt.get_cmap('gray'))
    plt.hold(True)
    plt.imshow(target_pred, alpha=0.7)
    plt.title('Predicted target - accuracy_score : %s' % round(score, 3))

    fig2 = plt.figure(2)
    plt.imshow(img, cmap=plt.get_cmap('gray'))
    plt.hold(True)
    plt.imshow(target_true, alpha=0.7)
    plt.title('True target')

    plt.show()
开发者ID:charleygros,项目名称:AxonSegmentation,代码行数:22,代码来源:visualization.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python pylab.get_current_fig_manager函数代码示例发布时间:2022-05-27
下一篇:
Python pylab.gcf函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap