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

Python colors.LinearSegmentedColormap类代码示例

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

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



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

示例1: cmapFromName

def cmapFromName(cmapname, ncols=256, bad=None):
    """
        Do we need this?
    """
    if not bad:
        bad = [1.0, 1.0, 1.0, 0.0]

    cmap = mpl.cm.get_cmap('jet', ncols)

    if cmapname is not None:

        if cmapname == 'b2r':
            cmap = mpl.colors.LinearSegmentedColormap('my_colormap',
                                                      cdict, ncols)
        elif cmapname == 'viridis' and StrictVersion(mpl.__version__) < StrictVersion('1.5.0'):
            print("Mpl:", mpl.__version__, " using HB viridis")
            cmap = LinearSegmentedColormap.from_list('viridis', viridis_data[::-1])
        elif cmapname == 'viridis_r':
            print("Using HB viridis_r")
            cmap = LinearSegmentedColormap.from_list('viridis', viridis_data)
        else:
            try:
                cmap = mpl.cm.get_cmap(cmapname, ncols)
            except Exception as e:
                print("Could not retrieve colormap ", cmapname, e)

    cmap.set_bad(bad)
    return cmap
开发者ID:dongxu-cug,项目名称:gimli,代码行数:28,代码来源:colorbar.py


示例2: get_colorMap_heat

def get_colorMap_heat():
    """ according to the colorweel heat"""
    color1 = np.array([0.0,14.,161.])/255.
    color2 = np.array([0., 125., 11.])/255.
    color3 = np.array([255.,255.,255.])/255.
    color4 = np.array([255., 172., 0.])/255.
#    color5 = np.array([ 184., 0.,18.])/255.
    color5 = np.array([ 163., 0.,119.])/255.
    cdict = {'red':   ((0.0, color1[0], color1[0]),
                       (0.25,color2[0] ,color2[0]),
                       (0.5,color3[0] ,color3[0]),
                       (0.75,color4[0] ,color4[0]),
                       (1.00,color5[0] ,color5[0])),
    
             'green': ((0.0, color1[1], color1[1]),
                       (0.25,color2[1] , color2[1]),
                       (0.5,color3[1] ,color3[1]),
                       (0.75,color4[1] ,color4[1]),
                       (1.0,color5[1] ,color5[1])),
    
             'blue':  ((0.0, color1[2], color1[2]),
                       (0.25, color2[2], color2[2]),
                       (0.5, color3[2] ,color3[2]),
                       (0.75,color4[2] ,color4[2]),
                       (1.0,color5[2] ,color5[2]))
            }
    
    hag_cmap  = LinearSegmentedColormap('hag_cmap',cdict)
    hag_cmap.set_bad('black')
    return hag_cmap
开发者ID:hagne,项目名称:hagpack,代码行数:30,代码来源:hagmods.py


示例3: get_colorMap_intensity_r

def get_colorMap_intensity_r():
    """ according to the colorweel intensity II"""
    color5 = [0.0,4./255,76./255] 
    color4 = [49./255., 130./255., 0.0]
    color3 = [1.,197./255.,98./255.]
    color2 = [245./255., 179./255., 223./255.]
    color1 = [ 216./255., 1.0,1.0]
    cdict = {'red':   ((0.0, color1[0], color1[0]),
                       (0.25,color2[0] ,color2[0]),
                       (0.5,color3[0] ,color3[0]),
                       (0.75,color4[0] ,color4[0]),
                       (1.00,color5[0] ,color5[0])),
    
             'green': ((0.0, color1[1], color1[1]),
                       (0.25,color2[1] , color2[1]),
                       (0.5,color3[1] ,color3[1]),
                       (0.75,color4[1] ,color4[1]),
                       (1.0,color5[1] ,color5[1])),
    
             'blue':  ((0.0, color1[2], color1[2]),
                       (0.25, color2[2], color2[2]),
                       (0.5, color3[2] ,color3[2]),
                       (0.75,color4[2] ,color4[2]),
                       (1.0,color5[2] ,color5[2]))
            }
    
    hag_cmap  = LinearSegmentedColormap('hag_cmap',cdict)
    hag_cmap.set_bad('black')
    return hag_cmap
开发者ID:hagne,项目名称:hagpack,代码行数:29,代码来源:hagmods.py


示例4: get_colorMap_water

def get_colorMap_water():
    """elevation map according to a tundra climate """
    colors = []
#     color.append(np.array([0.,0.,0.])/255.) #white for ice
#     blue = np.array([ 0., 0., 50])/255.
    
    blue = np.array([161., 190., 255.]) / 255.
    colors.append(blue)
    colors.append(blue)
#     colors.append(np.array([39., 62., 44.])/255.)
#     colors.append(np.array([77.,102.,70.])/255.)
#     colors.append(np.array([126., 129., 110.])/255.)
#     colors.append(np.array([ 95., 93.,94.])/255.)
#     colors.append(np.array([1.,1.,1.])) #white for ice
    
    steps = np.linspace(0,1,len(colors))
#     print(len(colors))
#    print(steps)
    red = []
    green = []
    blue = []
    
    for e,c in enumerate(colors):
        red.append((steps[e],c[0],c[0])) 
        green.append((steps[e],c[1],c[1])) 
        blue.append((steps[e],c[2],c[2])) 
        
    cdict = {'red':  red,
             'green': green,
             'blue':  blue
            }
    
    hag_cmap  = LinearSegmentedColormap('svalbard',cdict)
    hag_cmap.set_bad(np.array([ 0., 0.,0.,0]))
    return hag_cmap
开发者ID:hagne,项目名称:hagpack,代码行数:35,代码来源:svalbard.py


示例5: cmap_powerlaw_adjust

def cmap_powerlaw_adjust(cmap, a):
    '''
    returns a new colormap based on the one given
    but adjusted via power-law:

    newcmap = oldcmap**a
    '''
    if a < 0.:
        return cmap
    cdict = copy(cmap._segmentdata)
    def fn(x):
        return (x[0]**a, x[1], x[2])
    for key in ('red','green','blue'):
        try:
            cdict[key] = map(fn, cdict[key])
            cdict[key].sort()
            assert (cdict[key][0]<0 or cdict[key][-1]>1), \
                "Resulting indices extend out of the [0, 1] segment."
        except TypeError:
            def fngen(f):
                def fn(x):
                    return f(x)**a
                return fn
            cdict[key] = fngen(cdict[key])
    newcmap = LinearSegmentedColormap('colormap',cdict,1024)
    newcmap.set_bad(cmap(np.nan))
    return newcmap
开发者ID:theodoregoetz,项目名称:clas12-online-monitor,代码行数:27,代码来源:cmap.py


示例6: demo_compositing

def demo_compositing(im_r, im_g, im_b, im_rgb):
  fig = plt.figure(3)
  grid = ImageGrid(fig, 222,
                  nrows_ncols = (2, 2),
                  axes_pad = 0.1,
                  )

  cm_red = LinearSegmentedColormap.from_list('cm_black_red',
                                             [cm.colors.cnames['black'], cm.colors.cnames['red']]) 
  cm_green = LinearSegmentedColormap.from_list('cm_black_green',
                                               [cm.colors.cnames['black'], cm.colors.cnames['green']])
  cm_blue= LinearSegmentedColormap.from_list('cm_black_blue',
                                             [cm.colors.cnames['black'], cm.colors.cnames['blue']])

  im_grid = [im_r, im_g, im_b, im_rgb]

  color_maps = [cm_red, cm_green, cm_blue, None]

  for i in range(4):
    cmap = color_maps[i]
    grid[i].imshow(im_grid[i], cmap = cmap, interpolation = 'nearest')
# The AxesGrid object work as a list of axes.


  plt.show()
开发者ID:m-b-u,项目名称:vsite-graf,代码行数:25,代码来源:16_rgb.py


示例7: __init__

 def __init__(self, name, segmented_data, index=None, **kwargs):
     if index is None:
         # If index not given, RGB colors are evenly-spaced in colormap.
         index = np.linspace(0, 1, len(segmented_data['red']))
     for key, value in segmented_data.items():
         # Combine color index with color values.
         segmented_data[key] = zip(index, value)
     segmented_data = dict((key, [(x, y, y) for x, y in value])
                           for key, value in segmented_data.items())
     LinearSegmentedColormap.__init__(self, name, segmented_data, **kwargs)
开发者ID:cyanut,项目名称:ca1-3d,代码行数:10,代码来源:get_ca1.py


示例8: __init__

    def __init__(self):
        aggr1=0.2
        aggr2 = 0.2
        #fitnessCmap=LinearSegmentedColormap.from_list('fitness_map',[(aggr1,1,aggr1),(1,1,aggr1),(1,aggr1,aggr1)])
        fitnessCmap = LinearSegmentedColormap.from_list('fitness_map',[(0, 1-aggr1, 0), (1-aggr1, 1-aggr1, 0), (1-aggr1, 0, 0)])
        #complexityCmap = LinearSegmentedColormap.from_list('complexity_map', [(1,1,1),(aggr2, 1, 1), (aggr2,aggr2,1),(aggr2, aggr2, aggr2)])
        complexityCmap = LinearSegmentedColormap.from_list('complexity_map',[(0.6, 0.6, 0.9),(0, 0, 0.3)])

        self.complexity = complexityCmap#plt.get_cmap("cool")
        self.globalm = fitnessCmap
        self.localm = fitnessCmap#plt.get_cmap("RdYlGn")
开发者ID:Arkantus,项目名称:RFGraph,代码行数:11,代码来源:ColorMaps.py


示例9: newgray

def newgray():
    """ Modified version of Oranges."""
    oranges = cm.get_cmap("gray", 100)
    array = oranges(np.arange(100))
    array = array[40:]
    cmap = LinearSegmentedColormap.from_list("newgray", array)
    cm.register_cmap(name='newgray', cmap=cmap)
    array = array[::-1]
    cmap = LinearSegmentedColormap.from_list("newgray_r", array)
    cm.register_cmap(name='newgray_r', cmap=cmap)
    return
开发者ID:kadubarbosa,项目名称:hydrakin,代码行数:11,代码来源:newcolorbars.py


示例10: __init__

    def __init__(self, name, color_data, index=None, **kwargs):
        if not hasattr(color_data, 'keys'):
            color_data = rgb_list_to_colordict(color_data)

        if index is None:
            # If index not given, RGB colors are evenly-spaced in colormap.
            index = np.linspace(0, 1, len(color_data['red']))

        # Adapt color_data to the form expected by LinearSegmentedColormap.
        color_data = dict((key, [(x, y, y) for x, y in zip(index, value)])
                          for key, value in color_data.items())
        LinearSegmentedColormap.__init__(self, name, color_data, **kwargs)
开发者ID:MerlinSmiles,项目名称:mpltools,代码行数:12,代码来源:color.py


示例11: pl_hess_diag

def pl_hess_diag(
    gs, gs_y1, gs_y2, x_min_cmd, x_max_cmd, y_min_cmd, y_max_cmd, x_ax, y_ax,
        lkl_method, hess_xedges, hess_yedges, hess_x, hess_y, HD):
    """
    Hess diagram of observed minus best match synthetic cluster.
    """
    ax = plt.subplot(gs[gs_y1:gs_y2, 2:4])
    # Set plot limits
    plt.xlim(x_min_cmd, x_max_cmd)
    plt.ylim(y_min_cmd, y_max_cmd)
    # Set axis labels
    plt.xlabel('$' + x_ax + '$', fontsize=18)
    # Set minor ticks
    ax.minorticks_on()
    ax.xaxis.set_major_locator(MultipleLocator(1.0))
    if gs_y1 == 0:
        ax.set_title("Hess diagram (observed - synthetic)", fontsize=10)
    for x_ed in hess_xedges:
        # vertical lines
        ax.axvline(x_ed, linestyle=':', lw=.8, color='k', zorder=1)
    for y_ed in hess_yedges:
        # horizontal lines
        ax.axhline(y_ed, linestyle=':', lw=.8, color='k', zorder=1)
    if HD.any():
        # Add text box.
        if HD.min() < 0:
            plt.scatter(-100., -100., marker='s', lw=0., s=60, c='#0B02F8',
                        label='{}'.format(int(HD.min())))
        if HD.max() > 0:
            plt.scatter(-100., -100., marker='s', lw=0., s=60, c='#FB0605',
                        label='{}'.format(int(HD.max())))
        # Define custom colorbar.
        if HD.min() == 0:
            cmap = LinearSegmentedColormap.from_list(
                'mycmap', [(0, 'white'), (1, 'red')])
        else:
            # Zero point for empty bins which should be colored in white.
            zero_pt = (0. - HD.min()) / float(HD.max() - HD.min())
            N = 256.
            zero_pt0 = np.floor(zero_pt * (N - 1)) / (N - 1)
            zero_pt1 = np.ceil(zero_pt * (N - 1)) / (N - 1)
            cmap = LinearSegmentedColormap.from_list(
                'mycmap', [(0, 'blue'), (zero_pt0, 'white'), (zero_pt1,
                           'white'), (1, 'red')], N=N)
        ax.pcolormesh(hess_x, hess_y, HD, cmap=cmap, vmin=HD.min(),
                      vmax=HD.max(), zorder=1)
        # Legend.
        handles, labels = ax.get_legend_handles_labels()
        leg = ax.legend(
            handles, labels, loc='lower right', scatterpoints=1, ncol=2,
            columnspacing=.2, handletextpad=-.3, fontsize=10)
        leg.get_frame().set_alpha(0.7)
开发者ID:asteca,项目名称:ASteCA,代码行数:52,代码来源:mp_best_fit2.py


示例12: _create_overlay_map

def _create_overlay_map():
    #transparent colormap
    global _over_red
    r, g, b = plotParams['mask']['color']
    cdict = {'red': ((0.0, r, r),
                     (1.0, r, r)),
             'green': ((0.0, g, g),
                       (1.0, g, g)),
             'blue': ((0.0, b, b),
                      (1.0, b, b))
            }
    _over_red = LinearSegmentedColormap('MaskOver', cdict)
    _over_red.set_bad(alpha=0)
开发者ID:theilen,项目名称:PyMRR,代码行数:13,代码来源:mrrplot.py


示例13: temp_style_file

def temp_style_file(name):
    """ A context manager for creating an empty style file in the expected path.
    """
    stylelib_path = USER_LIBRARY_PATHS[0]
    if not os.path.exists(stylelib_path):
        os.makedirs(stylelib_path)
    srcname = os.path.abspath(os.path.join(os.path.dirname(__file__),name))
    dstname = os.path.join(stylelib_path, os.path.basename(name))
    if not os.path.exists(srcname):
        raise RuntimeError('Cannot use file at "' + srcname + '". This file does not exist.')
    if os.path.exists(dstname):
        #raise RuntimeError('Cannot create a temporary file at "' + dstname + '". This file exists already.')
        warnings.warn('Overwriting the temporary file at "' + dstname + '".')
    
    #with open(filename, 'w'):
    #    pass
    
    shutil.copy2(srcname, dstname)
    
    
    rgb = [
      (  0./255. ,   0./255. ,   0./255.),     
      (  0./255. , 102./255. ,  51./255.),
      #(114./255. , 121./255. , 126./255.),
      ( 91./255. , 172./255. ,  38./255.),
      (217./255. , 220./255. , 222./255.),
      (255./255. , 255./255. , 255./255.)
      ]

    # create map and register it together with reversed colours
    maps = []
    maps.append(LinearSegmentedColormap.from_list('IPU'  , rgb))
    maps.append(LinearSegmentedColormap.from_list('IPU_r', rgb[::-1]))

    for cmap in maps:
        mplcm.register_cmap(cmap=cmap)
        #self._color_maps[cmap.name] = cmap
    
    yield
    os.remove(dstname)



#print('# styles available:', len(plt.style.available))
#
#with temp_style_file('dummy.mplstyle'):
#    print('# before reload:', len(plt.style.available))
#
#    plt.style.reload_library()
#    print('# after reload:', len(plt.style.available))
开发者ID:IPUdk,项目名称:iputemplates,代码行数:50,代码来源:ipumpl.py


示例14: green_white

def green_white(levels=10):
    """ Generate a colormap from green to white.
    
    """
    colors =[(0., 0.5, 0.),
             (1., 1., 1.)]
    return LinearSegmentedColormap.from_list(colors=colors, name='green_white', N=levels)
开发者ID:ggarin,项目名称:alep,代码行数:7,代码来源:alep_color.py


示例15: generate_cmap

def generate_cmap(colors):
    values = range(len(colors))
    vmax = np.ceil(np.max(values))
    color_list = []
    for v, c in zip(values, colors):
        color_list.append( ( v/ vmax, c) )
    return LinearSegmentedColormap.from_list('custom_cmap', color_list)
开发者ID:TakakiNishio,项目名称:machine_learning,代码行数:7,代码来源:data_generator_3d.py


示例16: heat_map

    def heat_map(self, cmap='RdYlGn', vmin=None, vmax=None, font_cmap=None):
        if cmap is None:
            carr = ['#d7191c', '#fdae61', '#ffffff', '#a6d96a', '#1a9641']
            cmap = LinearSegmentedColormap.from_list('default-heatmap', carr)

        if isinstance(cmap, basestring):
            cmap = get_cmap(cmap)
        if isinstance(font_cmap, basestring):
            font_cmap = get_cmap(font_cmap)

        vals = self.actual_values.astype(float)
        if vmin is None:
            vmin = vals.min().min()
        if vmax is None:
            vmax = vals.max().max()
        norm = (vals - vmin) / (vmax - vmin)
        for ridx in range(self.nrows):
            for cidx in range(self.ncols):
                v = norm.iloc[ridx, cidx]
                if np.isnan(v):
                    continue
                color = cmap(v)
                hex = rgb2hex(color)
                styles = {'BACKGROUND': HexColor(hex)}
                if font_cmap is not None:
                    styles['TEXTCOLOR'] = HexColor(rgb2hex(font_cmap(v)))
                self.iloc[ridx, cidx].apply_styles(styles)
        return self
开发者ID:georgebdavis,项目名称:tia,代码行数:28,代码来源:table.py


示例17: swap_colors

def swap_colors(json_file_path):
    '''
    Switches out color ramp in meta.json files.
    Uses custom color ramp if provided and valid; otherwise falls back to nextstrain default colors.
    N.B.: Modifies json in place and writes to original file path.
    '''
    j = json.load(open(json_file_path, 'r'))
    color_options = j['color_options']

    for k,v in color_options.items():
        if 'color_map' in v:
            categories, colors = zip(*v['color_map'])

            ## Use custom colors if provided AND present for all categories in the dataset
            if custom_colors and all([category in custom_colors for category in categories]):
                colors = [ custom_colors[category] for category in categories ]

            ## Expand the color palette if we have too many categories
            elif len(categories) > len(default_colors):
                from matplotlib.colors import LinearSegmentedColormap, to_hex
                from numpy import linspace
                expanded_cmap = LinearSegmentedColormap.from_list('expanded_cmap', default_colors[-1], N=len(categories))
                discrete_colors = [expanded_cmap(i) for i in linspace(0,1,len(categories))]
                colors = [to_hex(c).upper() for c in discrete_colors]

            else: ## Falls back to default nextstrain colors
                colors = default_colors[len(categories)] # based on how many categories are present; keeps original ordering

            j['color_options'][k]['color_map'] = map(list, zip(categories, colors))

    json.dump(j, open(json_file_path, 'w'), indent=1)
开发者ID:blab,项目名称:nextstrain-augur,代码行数:31,代码来源:swap_colors.py


示例18: get_color_map

def get_color_map(num_states):
    colours = plt.cm.viridis(np.linspace(0, 1, num_states))
    colormap = {i: colours[i] for i in range(num_states)}
    cmap = LinearSegmentedColormap.from_list('name',
                                             list(colormap.values()),
                                             num_states)
    return colormap, cmap
开发者ID:NLeSC,项目名称:UKMovementSensing,代码行数:7,代码来源:hsmm.py


示例19: get_with_white_added

def get_with_white_added(cm_name_default, white_start=0.0, white_end=0.1,
                         ncolors_out=100):

    cmap = cm.get_cmap(cm_name_default)
    ncolors = cmap.N


    clist = []

    lower = []
    if white_start > 0:
        lower = cmap(np.linspace(0, white_start, int(white_start * ncolors)))
    clist.append(lower)

    white = np.ones((int((white_end - white_start) * ncolors), 4))
    clist.append(white)

    upper = []
    if white_end < 1:
        upper = cmap(np.linspace(white_end, 1, int((1 - white_end) * ncolors)))
    clist.append(upper)

    colors = np.vstack(tuple([p for p in clist if len(p) > 0]))

    return LinearSegmentedColormap.from_list("mycmap", colors, N=ncolors_out)
开发者ID:guziy,项目名称:RPN,代码行数:25,代码来源:custom_colormaps.py


示例20: plot_confusion_matrix

def plot_confusion_matrix(model_name, conf_matrix, labels, save, cmap, graph_fn='cfm.png'):

    startcolor = '#cccccc'
    midcolor = '#08519c'
    endcolor = '#08306b'

    b_g2 = LinearSegmentedColormap.from_list('B_G2', [startcolor, midcolor, endcolor])

    fig = plt.figure()
    ax = fig.add_subplot(111)
    cax = ax.matshow(conf_matrix, cmap=b_g2)
    fig.colorbar(cax)
    plt.title('Jeeves Confusion Matrix \n', fontsize=16)
    ax.set_xticklabels([''] + labels, fontsize=13)
    ax.set_yticklabels([''] + labels, fontsize=13)
    ax.xaxis.set_ticks_position('none')
    ax.yaxis.set_ticks_position('none')
    spines_to_remove = ['top', 'right', 'left', 'bottom']
    # for spine in spines_to_remove:
    #     ax.spines[spine].set_visible(False)
    plt.xlabel('Predicted', fontsize=14)
    plt.ylabel('Actual', fontsize=14)
    if save:
        plt.savefig(os.path.join(graph_dir, graph_fn))
    plt.show()
开发者ID:nyghtowl,项目名称:Code_Name_Jeeves,代码行数:25,代码来源:evaluate_model.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python colors.Normalize类代码示例发布时间:2022-05-27
下一篇:
Python colors.LightSource类代码示例发布时间: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