The simplest way to create such a colormap is via LinearSegmentedColormap.from_list('', ['b', 'k', 'k', 'r'])
. This divides the colors evenly, so pure black occupying 1/3rd of the range.
The function also allows to position the colors, via tuples of the form (position
, color
) with position
ranging from 0
at the left (bottom) to 1
at the right (top). Below is an example where black occupies 10% of the range.
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.cm import ScalarMappable
import numpy as np
cmap1 = LinearSegmentedColormap.from_list('', ['b', 'k', 'k', 'r'])
plt.colorbar(ScalarMappable(cmap=cmap1), orientation='horizontal',
ticks=np.linspace(0,1,11), label='pure black occupies 1/3rd')
width = 0.1
cmap2 = LinearSegmentedColormap.from_list('', [(0, 'b'), ((1 - width) / 2, 'k'), ( (1 + width) / 2, 'k'), (1, 'r')])
plt.colorbar(ScalarMappable(cmap=cmap2), orientation='horizontal',
ticks=np.linspace(0,1,11), label=f'pure black occupies {width}')
plt.show()