本文整理汇总了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: cmapFromName
# 需要导入模块: from matplotlib.colors import LinearSegmentedColormap [as 别名]
# 或者: from matplotlib.colors.LinearSegmentedColormap import from_list [as 别名]
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
示例2: demo_compositing
# 需要导入模块: from matplotlib.colors import LinearSegmentedColormap [as 别名]
# 或者: from matplotlib.colors.LinearSegmentedColormap import from_list [as 别名]
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()
示例3: _make_STMView_colormap
# 需要导入模块: from matplotlib.colors import LinearSegmentedColormap [as 别名]
# 或者: from matplotlib.colors.LinearSegmentedColormap import from_list [as 别名]
def _make_STMView_colormap(fileName, name='my_cmap'):
if fileName.endswith('.mat'):
matFile = _loadmat(_path + fileName)
for key in matFile:
if key not in ['__version__', '__header__', '__globals__']:
return _LSC.from_list(name, matFile[key])
elif fileName.endswith('.txt'):
txtFile = _np.loadtxt(_path + fileName)
return _LSC.from_list(name, txtFile)
示例4: __init__
# 需要导入模块: from matplotlib.colors import LinearSegmentedColormap [as 别名]
# 或者: from matplotlib.colors.LinearSegmentedColormap import from_list [as 别名]
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")
示例5: newgray
# 需要导入模块: from matplotlib.colors import LinearSegmentedColormap [as 别名]
# 或者: from matplotlib.colors.LinearSegmentedColormap import from_list [as 别名]
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
示例6: pl_hess_diag
# 需要导入模块: from matplotlib.colors import LinearSegmentedColormap [as 别名]
# 或者: from matplotlib.colors.LinearSegmentedColormap import from_list [as 别名]
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)
示例7: temp_style_file
# 需要导入模块: from matplotlib.colors import LinearSegmentedColormap [as 别名]
# 或者: from matplotlib.colors.LinearSegmentedColormap import from_list [as 别名]
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))
示例8: heatmap
# 需要导入模块: from matplotlib.colors import LinearSegmentedColormap [as 别名]
# 或者: from matplotlib.colors.LinearSegmentedColormap import from_list [as 别名]
def heatmap(cea, synchronous=True):
data = cea.grid.get_heat_data()
fig, ax = plt.subplots()
cmap = LinearSegmentedColormap.from_list('my cmap', ['black', 'white'])
heatmap_plot = ax.imshow(data, interpolation='nearest', cmap=cmap, vmin=0, vmax=1.0)
def init():
heatmap_plot.set_data(cea.grid.get_heat_data())
return heatmap_plot
def animate(i):
if i > 2:
cea.iterate_population() if synchronous else cea.iterate_individual()
heatmap_plot.set_data(cea.grid.get_heat_data())
return heatmap
anim = animation.FuncAnimation(fig, animate, init_func=init, frames=150)
plt.axis('off')
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
fig.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=None, hspace=None)
anim.save('gifs/slash_final.gif', writer='imagemagick')
plt.show()
示例9: plot_confusion_matrix
# 需要导入模块: from matplotlib.colors import LinearSegmentedColormap [as 别名]
# 或者: from matplotlib.colors.LinearSegmentedColormap import from_list [as 别名]
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()
示例10: 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)
示例11: get_color_map
# 需要导入模块: from matplotlib.colors import LinearSegmentedColormap [as 别名]
# 或者: from matplotlib.colors.LinearSegmentedColormap import from_list [as 别名]
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
示例12: heat_map
# 需要导入模块: from matplotlib.colors import LinearSegmentedColormap [as 别名]
# 或者: from matplotlib.colors.LinearSegmentedColormap import from_list [as 别名]
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, str):
cmap = get_cmap(cmap)
if isinstance(font_cmap, str):
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
示例13: make_thresholded_slices
# 需要导入模块: from matplotlib.colors import LinearSegmentedColormap [as 别名]
# 或者: from matplotlib.colors.LinearSegmentedColormap import from_list [as 别名]
def make_thresholded_slices(regions, colors, display_mode='z', overplot=True, binarize=True, **kwargs):
""" Plots on axial slices numerous images
regions: Nibabel images
colors: List of colors (rgb tuples)
overplot: Overlay images?
binarize: Binarize images or plot full stat maps
"""
from matplotlib.colors import LinearSegmentedColormap
from nilearn import plotting as niplt
if binarize:
for reg in regions:
reg.get_data()[reg.get_data().nonzero()] = 1
for i, reg in enumerate(regions):
reg_color = LinearSegmentedColormap.from_list('reg1', [colors[i], colors[i]])
if i == 0:
plot = niplt.plot_stat_map(reg, draw_cross=False, display_mode=display_mode, cmap = reg_color, alpha=0.9, colorbar=False, **kwargs)
else:
if overplot:
plot.add_overlay(reg, cmap = reg_color, alpha=.72)
else:
plt.plot_stat_map(reg, draw_cross=False, display_mode=display_mode, cmap = reg_color, colorbar=False, **kwargs)
return plot
示例14: plot_colorblock
# 需要导入模块: from matplotlib.colors import LinearSegmentedColormap [as 别名]
# 或者: from matplotlib.colors.LinearSegmentedColormap import from_list [as 别名]
def plot_colorblock(values, vmin=0, vmax=1, nColors=12, colors=[(0.75, 0.15, 0.15), (1, 0.75, 0.15), (0.15, 0.75, 0.15)]):
"""
Create a colorblock figure. Default color scheme is red to yellow to green with 12 colors.
This function can be used to generate dashboards with simple color indicators in each cell.
Parameters
-----------
values : 2D np.array
Values to plot in the colorblock
vmin : float (optional)
Colomap minimum, default = 0
vmax : float (optional)
Colomap maximum, default = 1
num_colors : int (optional)
Number of colors in the colormap
colors : list (optional)
List of colors, colors can be specified in any way understandable by matplotlib.colors.ColorConverter.to_rgb().
Default is red to yellow to green.
"""
from matplotlib.colors import LinearSegmentedColormap
cmap = LinearSegmentedColormap.from_list(name='custom', colors = colors, N=nColors)
fig = plt.imshow(values, cmap=cmap, aspect='equal', vmin=vmin, vmax=vmax)
plt.axis('off')
fig.axes.get_xaxis().set_visible(False)
fig.axes.get_yaxis().set_visible(False)
示例15: 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=100):
"""
Truncates a colourmap.
Parameters
----------
cmap : `matplotlib.colors.LinearSegmentedColormap`
Input colourmap.
minval, maxval : float
Interval to sample (minval >= 0, maxval <= 1)
n : int
Sampling density.
Returns
-------
new_cmap : `matplotlib.colors.LinearSegmentedColormap`
Truncated colourmap.
"""
new_cmap = LinearSegmentedColormap.from_list(
"trunc({n},{a:.2f},{b:.2f})".format(n=cmap.name, a=minval, b=maxval), cmap(np.linspace(minval, maxval, n))
)
return new_cmap