如果您真的需要一个通用颜色图,您可以创建一个BoundaryNorm,其边界正好位于颜色值的中间:
from matplotlib import pyplot as plt
import matplotlib as mpl
def min_val(combinations, color):
return min([x for xs, cs in combinations for x, c in zip(xs, cs) if c == color])
def max_val(combinations, color):
return max([x for xs, cs in combinations for x, c in zip(xs, cs) if c == color])
fig, ax = plt.subplots(figsize=(6, 1))
fig.subplots_adjust(bottom=0.5)
colors = ['grey', 'red', 'white'] # ordered from lowest to highest
combinations = [[[-2.024131, -3.837179, -2.947026], ['white', 'grey', 'red']],
[[-2.343214, -4.110780, -1.029205], ['red', 'grey', 'white']]]
bounds = [min_val(combinations, 'grey'),
(max_val(combinations, 'grey') + min_val(combinations, 'red')) / 2,
(max_val(combinations, 'red') + min_val(combinations, 'white')) / 2,
max_val(combinations, 'white')]
cmap = mpl.colors.ListedColormap(colors)
norm = mpl.colors.BoundaryNorm(bounds, len(colors))
cbar = mpl.colorbar.ColorbarBase(ax, cmap=cmap,
norm=norm,
orientation='horizontal')
cbar.set_label("Boundary norm")
fig.show()
另一种方法结合了LinearSegmentedColormap 和TwoSlopeNorm:
colors = ['grey', 'red', 'white'] # ordered from lowest to highest
combinations = [[[-2.024131, -3.837179, -2.947026], ['white', 'grey', 'red']],
[[-2.343214, -4.110780, -1.029205], ['red', 'grey', 'white']]]
bounds = [(min_val(combinations, c) + max_val(combinations, c)) / 2 for c in colors]
fig, ax = plt.subplots(figsize=(6, 1))
fig.subplots_adjust(bottom=0.5)
cmap = mpl.colors.LinearSegmentedColormap.from_list('segmented', colors)
norm = mpl.colors.TwoSlopeNorm(vcenter=bounds[1], vmin=bounds[0], vmax=bounds[2])
cbar = mpl.colorbar.ColorbarBase(ax, cmap=cmap,
norm=norm,
orientation='horizontal')
cbar.set_label("TwoSlopeNorm")
fig.show()