本文整理匯總了Python中matplotlib.colors.LinearSegmentedColormap.from_list方法的典型用法代碼示例。如果您正苦於以下問題:Python LinearSegmentedColormap.from_list方法的具體用法?Python LinearSegmentedColormap.from_list怎麽用?Python LinearSegmentedColormap.from_list使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類matplotlib.colors.LinearSegmentedColormap
的用法示例。
在下文中一共展示了LinearSegmentedColormap.from_list方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: read_color_table
# 需要導入模塊: from matplotlib.colors import LinearSegmentedColormap [as 別名]
# 或者: from matplotlib.colors.LinearSegmentedColormap import from_list [as 別名]
def read_color_table(color_file):
'''
The method for reading the color file.
'''
colors = []
levels = []
if exists(color_file) is False:
raise Exception("Color file " + color_file + " does not exist")
fp = open(color_file, "r")
for line in fp:
if line.find('#') == -1 and line.find('/') == -1:
entry = line.split()
levels.append(eval(entry[0]))
colors.append((int(entry[1])/255.,int(entry[2])/255.,int(entry[3])/255.))
fp.close()
cmap = LinearSegmentedColormap.from_list("my_colormap",colors, N=len(levels), gamma=1.0)
return levels, cmap
示例2: colors2cmap
# 需要導入模塊: from matplotlib.colors import LinearSegmentedColormap [as 別名]
# 或者: from matplotlib.colors.LinearSegmentedColormap import from_list [as 別名]
def colors2cmap(*args, name=None):
"""Create a colormap from a list of given colors.
Parameters:
*args: Arbitrary number of colors (Named color, HEX or RGB).
name (str): Name with which the colormap is registered.
Returns:
LinearSegmentedColormap.
Examples:
>>> colors2cmap('darkorange', 'white', 'darkgreen', name='test')
"""
if len(args) < 2:
raise Exception("Give at least two colors.")
cmap_data = [_to_hex(c) for c in args]
cmap = colors.LinearSegmentedColormap.from_list(name, cmap_data)
plt.register_cmap(name, cmap)
return cmap
示例3: get_dark_cmaps
# 需要導入模塊: from matplotlib.colors import LinearSegmentedColormap [as 別名]
# 或者: from matplotlib.colors.LinearSegmentedColormap import from_list [as 別名]
def get_dark_cmaps():
"""Generate dark-themed colormaps for eye-friendly visualization.
Returns
-------
tuple
Two matplotlib colormaps. The first color map is for +/- image data
while the second is intended for strictly positive valued images.
"""
from matplotlib.colors import LinearSegmentedColormap
field_cols=['#3d9aff', '#111111', '#ff3d63']
field_cmap=LinearSegmentedColormap.from_list('field_cmap', field_cols)
struct_cols=['#212730', '#bcccdb']
struct_cmap=LinearSegmentedColormap.from_list('struct_cmap', struct_cols)
return field_cmap, struct_cmap
示例4: blue_red_colormap
# 需要導入模塊: from matplotlib.colors import LinearSegmentedColormap [as 別名]
# 或者: from matplotlib.colors.LinearSegmentedColormap import from_list [as 別名]
def blue_red_colormap(size=100, reverse=False, white_padding=1, ):
size = size - (size % 4)
ll = size // 4
clist = []
s1 = [0.5 + 0.5 / ll * x for x in range(ll)]
s2 = [1.0 / ll * x for x in range(ll)]
for x in s1:
clist.append([0.0, 0.0, x])
for x in s2:
clist.append([x, x, 1.0])
for x in range(white_padding):
clist.append([1.0, 1.0, 1.0])
for x in range(ll):
clist.append([1.0, s2[-x - 1], s2[-x - 1]])
for x in range(ll):
clist.append([s1[-x - 1], 0.0, 0.0])
if reverse:
clist = clist[::-1]
from matplotlib.colors import LinearSegmentedColormap
cmap = LinearSegmentedColormap.from_list('BuRd', clist)
return cmap
示例5: rgb_colormap
# 需要導入模塊: from matplotlib.colors import LinearSegmentedColormap [as 別名]
# 或者: from matplotlib.colors.LinearSegmentedColormap import from_list [as 別名]
def rgb_colormap(color='blue', size=100, reverse=False, white_padding=1, ):
ll = size - white_padding
clist = []
r = 1
g = 1
b = 1
if color == 'red':
r = 0.5
elif color == 'green':
g = 0.5
elif color == 'blue':
b = 0.5
else:
raise ValueError('Select "red", "green", or "blue" for color.')
for x in range(white_padding):
clist.append([1.0, 1.0, 1.0])
for x in range(white_padding, size, 1):
y = x - white_padding
clist.append([1.0 - 1.0 * r * y / ll, 1.0 - 1.0 * g * y / ll, 1.0 - 1.0 * b * y / ll])
if reverse:
clist = clist[::-1]
cmap = LinearSegmentedColormap.from_list(color, clist)
return cmap
示例6: _register_cmap_clip
# 需要導入模塊: from matplotlib.colors import LinearSegmentedColormap [as 別名]
# 或者: from matplotlib.colors.LinearSegmentedColormap import from_list [as 別名]
def _register_cmap_clip(name, original_cmap, alpha):
"""Create a color map with "over" and "under" values."""
from matplotlib.colors import LinearSegmentedColormap
cdata = _plt.cm.datad[original_cmap]
if isinstance(cdata, dict):
cmap = LinearSegmentedColormap(name, cdata)
else:
cmap = LinearSegmentedColormap.from_list(name, cdata)
cmap.set_over([alpha * c + 1 - alpha for c in cmap(1.0)[:3]])
cmap.set_under([alpha * c + 1 - alpha for c in cmap(0.0)[:3]])
_plt.cm.register_cmap(cmap=cmap)
# The 'coolwarm' colormap is based on the paper
# "Diverging Color Maps for Scientific Visualization" by Kenneth Moreland
# http://www.sandia.gov/~kmorel/documents/ColorMaps/
示例7: make_colormap
# 需要導入模塊: from matplotlib.colors import LinearSegmentedColormap [as 別名]
# 或者: from matplotlib.colors.LinearSegmentedColormap import from_list [as 別名]
def make_colormap(color_palette, N=256, gamma=1.0):
"""
Create a linear colormap from a color palette.
Parameters
----------
color_palette : str, list, or dict
A color string, list of color strings, or color palette dict
Returns
-------
cmap : LinearSegmentedColormap
A colormap object based on color_palette using linear segments.
"""
colors = extract_palette(color_palette)
rgb = map(hex2rgb, colors)
return LinearSegmentedColormap.from_list('custom', list(rgb),
N=N, gamma=1.0)
示例8: cmap2rgba
# 需要導入模塊: from matplotlib.colors import LinearSegmentedColormap [as 別名]
# 或者: from matplotlib.colors.LinearSegmentedColormap import from_list [as 別名]
def cmap2rgba(cmap=None, N=None, interpolate=True):
"""Convert a colormap into a list of RGBA values.
Parameters:
cmap (str): Name of a registered colormap.
N (int): Number of RGBA-values to return.
If ``None`` use the number of colors defined in the colormap.
interpolate (bool): Toggle the interpolation of values in the
colormap. If ``False``, only values from the colormap are
used. This may lead to the re-use of a color, if the colormap
provides less colors than requested. If ``True``, a lookup table
is used to interpolate colors (default is ``True``).
Returns:
ndarray: RGBA-values.
Examples:
>>> cmap2rgba('viridis', 5)
array([[ 0.267004, 0.004874, 0.329415, 1. ],
[ 0.229739, 0.322361, 0.545706, 1. ],
[ 0.127568, 0.566949, 0.550556, 1. ],
[ 0.369214, 0.788888, 0.382914, 1. ],
[ 0.993248, 0.906157, 0.143936, 1. ]])
"""
cmap = plt.get_cmap(cmap)
if N is None:
N = cmap.N
nlut = N if interpolate else None
if interpolate and isinstance(cmap, colors.ListedColormap):
# `ListedColormap` does not support lookup table interpolation.
cmap = colors.LinearSegmentedColormap.from_list('', cmap.colors)
return cmap(np.linspace(0, 1, N))
return plt.get_cmap(cmap.name, lut=nlut)(np.linspace(0, 1, N))
示例9: cmap_from_act
# 需要導入模塊: from matplotlib.colors import LinearSegmentedColormap [as 別名]
# 或者: from matplotlib.colors.LinearSegmentedColormap import from_list [as 別名]
def cmap_from_act(file, name=None):
"""Import colormap from Adobe Color Table file.
Parameters:
file (str): Path to act file.
name (str): Colormap name. Defaults to filename without extension.
Returns:
LinearSegmentedColormap.
"""
# Extract colormap name from filename.
if name is None:
name = os.path.splitext(os.path.basename(file))[0]
# Read binary file and determine number of colors
rgb = np.fromfile(file, dtype=np.uint8)
if rgb.shape[0] >= 770:
ncolors = rgb[768] * 2**8 + rgb[769]
else:
ncolors = 256
colors = rgb[:ncolors*3].reshape(ncolors, 3) / 255
# Create and register colormap...
cmap = LinearSegmentedColormap.from_list(name, colors, N=ncolors)
plt.register_cmap(cmap=cmap) # Register colormap.
# ... and the reversed colormap.
cmap_r = LinearSegmentedColormap.from_list(
name + '_r', np.flipud(colors), N=ncolors)
plt.register_cmap(cmap=cmap_r)
return cmap
示例10: cmap_from_txt
# 需要導入模塊: from matplotlib.colors import LinearSegmentedColormap [as 別名]
# 或者: from matplotlib.colors.LinearSegmentedColormap import from_list [as 別名]
def cmap_from_txt(file, name=None, N=-1, comments='%'):
"""Import colormap from txt file.
Reads colormap data (RGB/RGBA) from an ASCII file.
Values have to be given in [0, 1] range.
Parameters:
file (str): Path to txt file.
name (str): Colormap name. Defaults to filename without extension.
N (int): Number of colors.
``-1`` means all colors (i.e., the complete file).
comments (str): Character to start comments with.
Returns:
LinearSegmentedColormap.
"""
# Extract colormap name from filename.
if name is None:
name = os.path.splitext(os.path.basename(file))[0]
# Read binary file and determine number of colors
rgb = np.genfromtxt(file, comments=comments)
if N == -1:
N = np.shape(rgb)[0]
if np.min(rgb) < 0 or np.max(rgb) > 1:
raise Exception('RGB value out of range: [0, 1].')
# Create and register colormap...
cmap = LinearSegmentedColormap.from_list(name, rgb, N=N)
plt.register_cmap(cmap=cmap)
# ... and the reversed colormap.
cmap_r = LinearSegmentedColormap.from_list(
name + '_r', np.flipud(rgb), N=N)
plt.register_cmap(cmap=cmap_r)
return cmap
示例11: truncate_colormap
# 需要導入模塊: from matplotlib.colors import LinearSegmentedColormap [as 別名]
# 或者: from matplotlib.colors.LinearSegmentedColormap import from_list [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
示例12: discrete_colourmap
# 需要導入模塊: from matplotlib.colors import LinearSegmentedColormap [as 別名]
# 或者: from matplotlib.colors.LinearSegmentedColormap import from_list [as 別名]
def discrete_colourmap(N, base_cmap=None):
"""Creates an N-bin discrete colourmap from the specified input colormap.
Author: github.com/jakevdp adopted by DAV
Note: Modified so you can pass in the string name of a colourmap
or a Colormap object.
Arguments:
N (int): Number of bins for the discrete colourmap. I.e. the number
of colours you will get.
base_cmap (str or Colormap object): Can either be the name of a colourmap
e.g. "jet" or a matplotlib Colormap object
"""
print(type(base_cmap))
if isinstance(base_cmap, _mcolors.Colormap):
base = base_cmap
elif isinstance(base_cmap, str):
base = _plt.cm.get_cmap(base_cmap)
else:
print("Colourmap supplied is of type: ", type(base_cmap))
raise ValueError('Colourmap must either be a string name of a colormap, \
or a Colormap object (class instance). Please try again.')
color_list = base(_np.linspace(0, 1, N))
cmap_name = base.name + str(N)
return base.from_list(cmap_name, color_list, N)
示例13: opencv_rainbow
# 需要導入模塊: from matplotlib.colors import LinearSegmentedColormap [as 別名]
# 或者: from matplotlib.colors.LinearSegmentedColormap import from_list [as 別名]
def opencv_rainbow(resolution=1000):
# Construct the opencv equivalent of Rainbow
opencv_rainbow_data = (
(0.000, (1.00, 0.00, 0.00)),
(0.400, (1.00, 1.00, 0.00)),
(0.600, (0.00, 1.00, 0.00)),
(0.800, (0.00, 0.00, 1.00)),
(1.000, (0.60, 0.00, 1.00))
)
return LinearSegmentedColormap.from_list('opencv_rainbow', opencv_rainbow_data, resolution)
示例14: _cmap_from_image_path
# 需要導入模塊: from matplotlib.colors import LinearSegmentedColormap [as 別名]
# 或者: from matplotlib.colors.LinearSegmentedColormap import from_list [as 別名]
def _cmap_from_image_path(img_path):
img = Image.open(img_path)
img = img.resize((256, img.height))
colours = (img.getpixel((x, 0)) for x in range(256))
colours = [(r/255, g/255, b/255, a/255) for (r, g, b, a) in colours]
return LinearSegmentedColormap.from_list('from_image', colours)
示例15: swap_colors
# 需要導入模塊: from matplotlib.colors import LinearSegmentedColormap [as 別名]
# 或者: from matplotlib.colors.LinearSegmentedColormap import from_list [as 別名]
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)