当前位置: 首页 > 工具软件 > Colors > 使用案例 >

python colormap_Python colors.LinearSegmentedColormap方法代码示例

仲孙温文
2023-12-01

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

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

示例1: cmap_discretize

​点赞 6

# 需要导入模块: from matplotlib import colors [as 别名]

# 或者: from matplotlib.colors import LinearSegmentedColormap [as 别名]

def cmap_discretize(N, cmap):

"""Return a discrete colormap from the continuous colormap cmap.

Arguments:

cmap: colormap instance, eg. cm.jet.

N: number of colors.

Example:

x = resize(arange(100), (5,100))

djet = cmap_discretize(cm.jet, 5)

imshow(x, cmap=djet)

"""

if type(cmap) == str:

cmap = _plt.get_cmap(cmap)

colors_i = _np.concatenate((_np.linspace(0, 1., N), (0.,0.,0.,0.)))

colors_rgba = cmap(colors_i)

indices = _np.linspace(0, 1., N+1)

cdict = {}

for ki,key in enumerate(('red','green','blue')):

cdict[key] = [ (indices[i], colors_rgba[i-1,ki], colors_rgba[i,ki])

for i in range(N+1) ]

# Return colormap object.

return _mcolors.LinearSegmentedColormap(cmap.name + "_%d"%N, cdict, 1024)

开发者ID:LSDtopotools,项目名称:LSDMappingTools,代码行数:26,

示例2: plot_dist_f

​点赞 6

# 需要导入模块: from matplotlib import colors [as 别名]

# 或者: from matplotlib.colors import LinearSegmentedColormap [as 别名]

def plot_dist_f(v, o, prefix, suffix, summariesdir):

xkeys = range(len(v.dist_f))

ykeys = list(v.dist_f[0].keys())

f_share = np.ndarray([len(ykeys), len(xkeys)])

for x in range(f_share.shape[1]):

for y in range(f_share.shape[0]):

f_share[y, x] = v.dist_f[xkeys[x]][ykeys[y]]

ccmap = mplcolors.LinearSegmentedColormap('by_cmap', cdict2)

fig, ax = plt.subplots(dpi=300)

pcm = ax.imshow(f_share, origin='lower',

extent=[v.time[0], v.time[-1], ykeys[0], ykeys[-1]],

aspect='auto',

cmap=ccmap)

clb = fig.colorbar(pcm, ax=ax)

clb.set_label('share of given share of M13 wt fitness', y=0.5)

plt.title('Development of fitness distribution')

plt.ylabel('Fitness relative to wt M13 fitness')

plt.xlabel('Time [min]')

plt.savefig(os.path.join(summariesdir, "{}fitness_distribution_{}.png".format(prefix, suffix)))

plt.close()

开发者ID:igemsoftware2017,项目名称:AiGEM_TeamHeidelberg2017,代码行数:27,

示例3: createColormap

​点赞 6

# 需要导入模块: from matplotlib import colors [as 别名]

# 或者: from matplotlib.colors import LinearSegmentedColormap [as 别名]

def createColormap(color, min_factor=1.0, max_factor=0.95):

"""

Creates colormap with range 0-1 from white to arbitrary color.

Args:

color: Matplotlib-readable color representation. Examples: 'g', '#00FFFF', '0.5', [0.1, 0.5, 0.9]

min_factor(float): Float in the range 0-1, specifying the gray-scale color of the minimal plot value.

max_factor(float): Float in the range 0-1, multiplication factor of 'color' argument for maximal plot value.

Returns:

Colormap object to be used by matplotlib-functions

"""

rgb = colors.colorConverter.to_rgb(color)

cdict = {'red': [(0.0, min_factor, min_factor),

(1.0, max_factor*rgb[0], max_factor*rgb[0])],

'green': [(0.0, min_factor, min_factor),

(1.0, max_factor*rgb[1], max_factor*rgb[1])],

'blue': [(0.0, min_factor, min_factor),

(1.0, max_factor*rgb[2], max_factor*rgb[2])]}

return colors.LinearSegmentedColormap('custom', cdict)

开发者ID:christophmark,项目名称:bayesloop,代码行数:25,

示例4: gpf

​点赞 6

# 需要导入模块: from matplotlib import colors [as 别名]

# 或者: from matplotlib.colors import LinearSegmentedColormap [as 别名]

def gpf(self):

cmap = {"red": [], "green": [], "blue": []}

with open(self.filepath, "r") as f:

lastred = (0.0, 0.0, 0.0)

lastgreen = lastred

lastblue = lastred

line = f.readline()

while line:

if line[0] != "#":

data = [ast.literal_eval(numbyte) for numbyte in line.split()]

red = (data[0], lastred[2], data[1])

green = (data[0], lastgreen[2], data[2])

blue = (data[0], lastblue[2], data[3])

cmap["red"].append(red)

cmap["green"].append(green)

cmap["blue"].append(blue)

lastred = red

lastgreen = green

lastblue = blue

line = f.readline()

return dict(cmap=mclr.LinearSegmentedColormap("gpf", cmap))

开发者ID:CyanideCN,项目名称:PyCINRAD,代码行数:23,

示例5: gradient_cmap

​点赞 6

# 需要导入模块: from matplotlib import colors [as 别名]

# 或者: from matplotlib.colors import LinearSegmentedColormap [as 别名]

def gradient_cmap(gcolors, nsteps=256, bounds=None):

"""

Make a colormap that interpolates between a set of colors

"""

ncolors = len(gcolors)

if bounds is None:

bounds = np.linspace(0, 1, ncolors)

reds = []

greens = []

blues = []

alphas = []

for b, c in zip(bounds, gcolors):

reds.append((b, c[0], c[0]))

greens.append((b, c[1], c[1]))

blues.append((b, c[2], c[2]))

alphas.append((b, c[3], c[3]) if len(c) == 4 else (b, 1., 1.))

cdict = {'red': tuple(reds),

'green': tuple(greens),

'blue': tuple(blues),

'alpha': tuple(alphas)}

cmap = LinearSegmentedColormap('grad_colormap', cdict, nsteps)

return cmap

开发者ID:slinderman,项目名称:recurrent-slds,代码行数:27,

示例6: make_colormap

​点赞 6

# 需要导入模块: from matplotlib import colors [as 别名]

# 或者: from matplotlib.colors import LinearSegmentedColormap [as 别名]

def make_colormap(seq):

"""Return a LinearSegmentedColormap

seq: a sequence of floats and RGB-tuples. The floats should be increasing

and in the interval (0,1).

[from: https://stackoverflow.com/questions/16834861/create-own-colormap-using-matplotlib-and-plot-color-scale]

"""

seq = [(None,) * 3, 0.0] + list(seq) + [1.0, (None,) * 3]

cdict = {'red': [], 'green': [], 'blue': []}

for i, item in enumerate(seq):

if isinstance(item, float):

r1, g1, b1 = seq[i - 1]

r2, g2, b2 = seq[i + 1]

cdict['red'].append([item, r1, r2])

cdict['green'].append([item, g1, g2])

cdict['blue'].append([item, b1, b2])

return mcolors.LinearSegmentedColormap('CustomMap', cdict)

开发者ID:zsylvester,项目名称:meanderpy,代码行数:18,

示例7: make_colormap

​点赞 6

# 需要导入模块: from matplotlib import colors [as 别名]

# 或者: from matplotlib.colors import LinearSegmentedColormap [as 别名]

def make_colormap(seq):

"""

Return a LinearSegmentedColormap: http://stackoverflow.com/a/16836182

Args:

seq: a sequence of floats and RGB-tuples. The floats should be increasing

and in the interval (0,1).

"""

seq = [(None,) * 3, 0.0] + list(seq) + [1.0, (None,) * 3]

cdict = {'red': [], 'green': [], 'blue': []}

for i, item in enumerate(seq):

if isinstance(item, float):

r1, g1, b1 = seq[i - 1]

r2, g2, b2 = seq[i + 1]

cdict['red'].append([item, r1, r2])

cdict['green'].append([item, g1, g2])

cdict['blue'].append([item, b1, b2])

return mcolors.LinearSegmentedColormap('CustomMap', cdict)

开发者ID:DFO-Ocean-Navigator,项目名称:Ocean-Data-Map-Project,代码行数:19,

示例8: truncate_colormap

​点赞 5

# 需要导入模块: from matplotlib import colors [as 别名]

# 或者: from matplotlib.colors import LinearSegmentedColormap [as 别名]

def truncate_colormap(cmap, minval=0.0, maxval=1.0, n=-1):

"""

Truncates a standard matplotlib colourmap so

that you can use part of the colour range in your plots.

Handy when the colourmap you like has very light values at

one end of the map that can't be seen easily.

Arguments:

cmap (:obj: `Colormap`): A matplotlib Colormap object. Note this is not

a string name of the colourmap, you must pass the object type.

minval (int, optional): The lower value to truncate the colour map to.

colourmaps range from 0.0 to 1.0. Should be 0.0 to include the full

lower end of the colour spectrum.

maxval (int, optional): The upper value to truncate the colour map to.

maximum should be 1.0 to include the full upper range of colours.

n (int): Leave at default.

Example:

minColor = 0.00

maxColor = 0.85

inferno_t = truncate_colormap(_plt.get_cmap("inferno"), minColor, maxColor)

"""

cmap = _plt.get_cmap(cmap)

if n == -1:

n = cmap.N

new_cmap = _mcolors.LinearSegmentedColormap.from_list(

'trunc({name},{a:.2f},{b:.2f})'.format(name=cmap.name, a=minval, b=maxval),

cmap(_np.linspace(minval, maxval, n)))

return new_cmap

开发者ID:LSDtopotools,项目名称:LSDMappingTools,代码行数:32,

示例9: __call__

​点赞 5

# 需要导入模块: from matplotlib import colors [as 别名]

# 或者: from matplotlib.colors import LinearSegmentedColormap [as 别名]

def __call__(self, function, cmap):

return _mcolors.LinearSegmentedColormap('colormap', self.cdict, 1024)

开发者ID:LSDtopotools,项目名称:LSDMappingTools,代码行数:4,

示例10: cmap_discretize

​点赞 5

# 需要导入模块: from matplotlib import colors [as 别名]

# 或者: from matplotlib.colors import LinearSegmentedColormap [as 别名]

def cmap_discretize(self, cmap, N):

"""

Return a discrete colormap from the continuous colormap cmap.

From http://scipy.github.io/old-wiki/pages/Cookbook/Matplotlib/ColormapTransformations

Args:

cmap: colormap instance, eg. cm.jet.

N: number of colors.

Returns:

discrete colourmap

Author: FJC

"""

if type(cmap) == str:

cmap = plt.get_cmap(cmap)

colors_i = np.concatenate((np.linspace(0, 1., N), (0.,0.,0.,0.)))

colors_rgba = cmap(colors_i)

indices = np.linspace(0, 1., N+1)

cdict = {}

for ki,key in enumerate(('red','green','blue')):

cdict[key] = [ (indices[i], colors_rgba[i-1,ki], colors_rgba[i,ki]) for i in range(N+1) ]

# Return colormap object.

return _mcolors.LinearSegmentedColormap(cmap.name + "_%d"%N, cdict, 1024)

开发者ID:LSDtopotools,项目名称:LSDMappingTools,代码行数:31,

示例11: _generate_cmap

​点赞 5

# 需要导入模块: from matplotlib import colors [as 别名]

# 或者: from matplotlib.colors import LinearSegmentedColormap [as 别名]

def _generate_cmap(name, lutsize):

"""Generates the requested cmap from it's name *name*. The lut size is

*lutsize*."""

spec = datad[name]

# Generate the colormap object.

if 'red' in spec:

return colors.LinearSegmentedColormap(name, spec, lutsize)

else:

return colors.LinearSegmentedColormap.from_list(name, spec, lutsize)

开发者ID:ktraunmueller,项目名称:Computable,代码行数:13,代码来源:cm.py

示例12: register_cmap

​点赞 5

# 需要导入模块: from matplotlib import colors [as 别名]

# 或者: from matplotlib.colors import LinearSegmentedColormap [as 别名]

def register_cmap(name=None, cmap=None, data=None, lut=None):

"""

Add a colormap to the set recognized by :func:`get_cmap`.

It can be used in two ways::

register_cmap(name='swirly', cmap=swirly_cmap)

register_cmap(name='choppy', data=choppydata, lut=128)

In the first case, *cmap* must be a :class:`matplotlib.colors.Colormap`

instance. The *name* is optional; if absent, the name will

be the :attr:`~matplotlib.colors.Colormap.name` attribute of the *cmap*.

In the second case, the three arguments are passed to

the :class:`~matplotlib.colors.LinearSegmentedColormap` initializer,

and the resulting colormap is registered.

"""

if name is None:

try:

name = cmap.name

except AttributeError:

raise ValueError("Arguments must include a name or a Colormap")

if not cbook.is_string_like(name):

raise ValueError("Colormap name must be a string")

if isinstance(cmap, colors.Colormap):

cmap_d[name] = cmap

return

# For the remainder, let exceptions propagate.

if lut is None:

lut = mpl.rcParams['image.lut']

cmap = colors.LinearSegmentedColormap(name, data, lut)

cmap_d[name] = cmap

开发者ID:ktraunmueller,项目名称:Computable,代码行数:39,代码来源:cm.py

示例13: _generate_cmap

​点赞 5

# 需要导入模块: from matplotlib import colors [as 别名]

# 或者: from matplotlib.colors import LinearSegmentedColormap [as 别名]

def _generate_cmap(name, lutsize):

"""Generates the requested cmap from its *name*. The lut size is

*lutsize*."""

spec = datad[name]

# Generate the colormap object.

if 'red' in spec:

return colors.LinearSegmentedColormap(name, spec, lutsize)

elif 'listed' in spec:

return colors.ListedColormap(spec['listed'], name)

else:

return colors.LinearSegmentedColormap.from_list(name, spec, lutsize)

开发者ID:Relph1119,项目名称:GraphicDesignPatternByPython,代码行数:15,代码来源:cm.py

示例14: register_cmap

​点赞 5

# 需要导入模块: from matplotlib import colors [as 别名]

# 或者: from matplotlib.colors import LinearSegmentedColormap [as 别名]

def register_cmap(name=None, cmap=None, data=None, lut=None):

"""

Add a colormap to the set recognized by :func:`get_cmap`.

It can be used in two ways::

register_cmap(name='swirly', cmap=swirly_cmap)

register_cmap(name='choppy', data=choppydata, lut=128)

In the first case, *cmap* must be a :class:`matplotlib.colors.Colormap`

instance. The *name* is optional; if absent, the name will

be the :attr:`~matplotlib.colors.Colormap.name` attribute of the *cmap*.

In the second case, the three arguments are passed to

the :class:`~matplotlib.colors.LinearSegmentedColormap` initializer,

and the resulting colormap is registered.

"""

if name is None:

try:

name = cmap.name

except AttributeError:

raise ValueError("Arguments must include a name or a Colormap")

if not isinstance(name, str):

raise ValueError("Colormap name must be a string")

if isinstance(cmap, colors.Colormap):

cmap_d[name] = cmap

return

# For the remainder, let exceptions propagate.

if lut is None:

lut = mpl.rcParams['image.lut']

cmap = colors.LinearSegmentedColormap(name, data, lut)

cmap_d[name] = cmap

开发者ID:Relph1119,项目名称:GraphicDesignPatternByPython,代码行数:39,代码来源:cm.py

示例15: test_get_cmaps_registers_ocean_colour

​点赞 5

# 需要导入模块: from matplotlib import colors [as 别名]

# 或者: from matplotlib.colors import LinearSegmentedColormap [as 别名]

def test_get_cmaps_registers_ocean_colour(self):

ensure_cmaps_loaded()

cmap = cm.get_cmap('deep', 256)

self.assertTrue((type(cmap) is LinearSegmentedColormap) or (type(cmap) is ListedColormap))

开发者ID:dcs4cop,项目名称:xcube,代码行数:6,

示例16: test_get_cmaps_registers_snap_color

​点赞 5

# 需要导入模块: from matplotlib import colors [as 别名]

# 或者: from matplotlib.colors import LinearSegmentedColormap [as 别名]

def test_get_cmaps_registers_snap_color(self):

ensure_cmaps_loaded()

cmap_name = os.path.join(os.path.dirname(__file__), 'chl_DeM2_200.cpd')

cmap = _get_custom_colormap(cmap_name)

cm.register_cmap(cmap=cmap)

self.assertTrue((type(cmap) is LinearSegmentedColormap) or (type(cmap) is ListedColormap))

开发者ID:dcs4cop,项目名称:xcube,代码行数:8,

示例17: draw_meta

​点赞 5

# 需要导入模块: from matplotlib import colors [as 别名]

# 或者: from matplotlib.colors import LinearSegmentedColormap [as 别名]

def draw_meta(scoret, akeys, xkeys, ykeys, prefix, suffix, xlabel, ylabel, title, summariesdir):

ccmap = mplcolors.LinearSegmentedColormap('by_cmap', cdict)

count = 1

for fdraw in range(scoret.shape[0]):

fig, ax = plt.subplots(dpi=300)

pcm = ax.imshow(scoret[fdraw, :, :], origin='lower',

extent=[xkeys[0], xkeys[-1], ykeys[0], ykeys[-1]],

aspect='auto',

cmap = ccmap,

clim=[-1, 1])

clb = fig.colorbar(pcm, ax=ax, extend='both',

ticks=np.asarray([-1, -0.75, -0.5, -0.25, 0, 0.25, 0.5, 0.75, 1]))

clb.set_ticklabels([-0, -25, -50, -75, 100, 75, 50, 25, 0])

clb.set_label('# of epochs the phage concentration accepted', y=0.5)

clb.set_clim(-1, 1)

plt.title(title + ' = {:.3f}'.format(akeys[fdraw]))

plt.ylabel(ylabel)

plt.xlabel(xlabel)

plt.savefig(os.path.join(summariesdir, "{}meta_a_{:.3f}_{}.png".format(prefix, akeys[fdraw], suffix)))

plt.close()

print('Saved {}th figure.'.format(count))

count += 1

开发者ID:igemsoftware2017,项目名称:AiGEM_TeamHeidelberg2017,代码行数:28,

示例18: plot_linearmap

​点赞 5

# 需要导入模块: from matplotlib import colors [as 别名]

# 或者: from matplotlib.colors import LinearSegmentedColormap [as 别名]

def plot_linearmap(cdict):

newcmp = LinearSegmentedColormap('testCmap', segmentdata=cdict, N=256)

rgba = newcmp(np.linspace(0, 1, 256))

fig, ax = plt.subplots(figsize=(4, 3), constrained_layout=True)

col = ['r', 'g', 'b']

for xx in [0.25, 0.5, 0.75]:

ax.axvline(xx, color='0.7', linestyle='--')

for i in range(3):

ax.plot(np.arange(256)/256, rgba[:, i], color=col[i])

ax.set_xlabel('index')

ax.set_ylabel('RGB')

plt.show()

开发者ID:holzschu,项目名称:python3_ios,代码行数:14,

示例19: make_colormap

​点赞 5

# 需要导入模块: from matplotlib import colors [as 别名]

# 或者: from matplotlib.colors import LinearSegmentedColormap [as 别名]

def make_colormap(seq):

""" Return a LinearSegmentedColormap

seq: a sequence of floats and RGB-tuples. The floats should be increasing

and in the interval (0,1).

"""

seq = [(None,) * 3, 0.0] + list(seq) + [1.0, (None,) * 3]

cdict = {'red': [], 'green': [], 'blue': []}

for i, item in enumerate(seq):

if isinstance(item, float):

r1, g1, b1 = seq[i - 1]

r2, g2, b2 = seq[i + 1]

cdict['red'].append([item, r1, r2])

cdict['green'].append([item, g1, g2])

cdict['blue'].append([item, b1, b2])

return mcolors.LinearSegmentedColormap('CustomMap', cdict)

开发者ID:MIC-DKFZ,项目名称:RegRCNN,代码行数:17,

示例20: cmap_xmap

​点赞 5

# 需要导入模块: from matplotlib import colors [as 别名]

# 或者: from matplotlib.colors import LinearSegmentedColormap [as 别名]

def cmap_xmap(function, cmap, name=None):

"""Applies function on the indices of colormap cmap. Beware, function

should map the [0, 1] segment to itself, or you are in for surprises."""

cmap = copy.deepcopy(cmap)

cdict = cmap._segmentdata

for key in cdict:

cdict[key] = sorted([(function(x[0]), x[1], x[2]) for x in cdict[key]])

if name is not None: cmap.name = name

return mcolors.LinearSegmentedColormap(cmap.name, cdict, cmap.N)

开发者ID:j08lue,项目名称:pycpt,代码行数:11,

示例21: test_cmap_from_cptcity_url

​点赞 5

# 需要导入模块: from matplotlib import colors [as 别名]

# 或者: from matplotlib.colors import LinearSegmentedColormap [as 别名]

def test_cmap_from_cptcity_url(self):

cmap = cmap_from_cptcity_url('ngdc/ETOPO1.cpt')

self.assertIsInstance(cmap, mcolors.LinearSegmentedColormap)

开发者ID:j08lue,项目名称:pycpt,代码行数:5,

示例22: test_cmap_from_cptcity_url_download

​点赞 5

# 需要导入模块: from matplotlib import colors [as 别名]

# 或者: from matplotlib.colors import LinearSegmentedColormap [as 别名]

def test_cmap_from_cptcity_url_download(self):

cmap = cmap_from_cptcity_url('ngdc/ETOPO1.cpt', download=True)

self.assertIsInstance(cmap, mcolors.LinearSegmentedColormap)

开发者ID:j08lue,项目名称:pycpt,代码行数:5,

示例23: _generate_cmap

​点赞 5

# 需要导入模块: from matplotlib import colors [as 别名]

# 或者: from matplotlib.colors import LinearSegmentedColormap [as 别名]

def _generate_cmap(name, lutsize):

"""Generates the requested cmap from it's name *name*. The lut size is

*lutsize*."""

spec = datad[name]

# Generate the colormap object.

with warnings.catch_warnings():

warnings.simplefilter("ignore", FutureWarning)

if 'red' in spec:

return colors.LinearSegmentedColormap(name, spec, lutsize)

else:

return colors.LinearSegmentedColormap.from_list(name, spec, lutsize)

开发者ID:YvZheng,项目名称:pycwr,代码行数:14,

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

 类似资料: