Created
January 23, 2019 12:27
-
-
Save grey-area/8a8cc40a721da1b2dc986fbda039f8da to your computer and use it in GitHub Desktop.
Making custom greyscale colormaps to emphasise parts of the scale
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
import matplotlib.pyplot as plt | |
# make_cmap function is from: http://schubert.atmos.colostate.edu/~cslocum/custom_cmap.html | |
def make_cmap(colors, position=None, bit=False): | |
''' | |
make_cmap takes a list of tuples which contain RGB values. The RGB | |
values may either be in 8-bit [0 to 255] (in which bit must be set to | |
True when called) or arithmetic [0 to 1] (default). make_cmap returns | |
a cmap with equally spaced colors. | |
Arrange your tuples so that the first color is the lowest value for the | |
colorbar and the last is the highest. | |
position contains values from 0 to 1 to dictate the location of each color. | |
''' | |
import matplotlib as mpl | |
import numpy as np | |
bit_rgb = np.linspace(0,1,256) | |
if position == None: | |
position = np.linspace(0,1,len(colors)) | |
else: | |
if len(position) != len(colors): | |
sys.exit("position length must be the same as colors") | |
elif position[0] != 0 or position[-1] != 1: | |
sys.exit("position must start with 0 and end with 1") | |
if bit: | |
for i in range(len(colors)): | |
colors[i] = (bit_rgb[colors[i][0]], | |
bit_rgb[colors[i][1]], | |
bit_rgb[colors[i][2]]) | |
cdict = {'red':[], 'green':[], 'blue':[]} | |
for pos, color in zip(position, colors): | |
cdict['red'].append((pos, color[0], color[0])) | |
cdict['green'].append((pos, color[1], color[1])) | |
cdict['blue'].append((pos, color[2], color[2])) | |
cmap = mpl.colors.LinearSegmentedColormap('my_colormap',cdict,256) | |
return cmap | |
colors1 = [ | |
(255, 255, 255), | |
(200, 200, 200), | |
(150, 150, 150), | |
(100, 100, 100), | |
(50, 50, 50), | |
(0, 0, 0), | |
] | |
colors2 = [ | |
(255, 255, 255), | |
(150, 150, 150), | |
(90, 90, 90), | |
(50, 50, 50), | |
(20, 20, 20), | |
(0, 0, 0), | |
] | |
my_cmap = make_cmap(colors2, bit=True) | |
plt.pcolor(np.random.rand(50, 50), cmap=my_cmap) | |
plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment