本文整理匯總了Python中matplotlib.colors.LinearSegmentedColormap方法的典型用法代碼示例。如果您正苦於以下問題:Python colors.LinearSegmentedColormap方法的具體用法?Python colors.LinearSegmentedColormap怎麽用?Python colors.LinearSegmentedColormap使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類matplotlib.colors
的用法示例。
在下文中一共展示了colors.LinearSegmentedColormap方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: cmap_discretize
# 需要導入模塊: 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)
示例2: plot_dist_f
# 需要導入模塊: 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()
示例3: createColormap
# 需要導入模塊: 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)
示例4: gpf
# 需要導入模塊: 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))
示例5: gradient_cmap
# 需要導入模塊: 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
示例6: make_colormap
# 需要導入模塊: 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)
示例7: make_colormap
# 需要導入模塊: 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)
示例8: __call__
# 需要導入模塊: from matplotlib import colors [as 別名]
# 或者: from matplotlib.colors import LinearSegmentedColormap [as 別名]
def __call__(self, function, cmap):
return _mcolors.LinearSegmentedColormap('colormap', self.cdict, 1024)
示例9: truncate_colormap
# 需要導入模塊: 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
示例10: cmap_discretize
# 需要導入模塊: 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)
示例11: _generate_cmap
# 需要導入模塊: 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)
示例12: register_cmap
# 需要導入模塊: 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
示例13: _generate_cmap
# 需要導入模塊: 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)
示例14: register_cmap
# 需要導入模塊: 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
示例15: test_get_cmaps_registers_ocean_colour
# 需要導入模塊: 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))