Skip to content

Commit bbaaa60

Browse files
authored
Update cm.py to register maps with matplotlib
This commit checks if matplotlib is available and, if it is, registers the colour maps. Each map is available via "cmocean_<map_name>", so that 'thermal' would be accessed, for example, by plt.pcolormesh(x, y, z, cmap = 'cmocean_thermal'). Alpha channels were also explicitly added and set to 1.
1 parent 64bc250 commit bbaaa60

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

cmocean/cm.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,14 @@
1515

1616
from . import tools
1717

18+
# If matplotlib is available, load it
19+
try:
20+
import matplotlib.colors as mplc
21+
import matplotlib.pyplot as plt
22+
do_registry = True
23+
except:
24+
do_registry = False
25+
1826
# Location of rgb files
1927
datadir = os.path.join(os.path.split(__file__)[0], 'rgb')
2028

@@ -33,6 +41,18 @@
3341
cmap_d[cmapname].name = cmapname
3442
cmap_d[cmapname + '_r'] = tools.cmap(rgb[::-1, :], N=256)
3543
cmap_d[cmapname + '_r'].name = cmapname + '_r'
44+
45+
# Register the cmap with matplotlib, if available
46+
if do_registry:
47+
rgb_with_alpha = np.zeros((rgb.shape[0],4))
48+
rgb_with_alpha[:,:3] = rgb
49+
rgb_with_alpha[:,3] = 1. #set alpha channel to 1
50+
reg_map = mplc.ListedColormap(rgb_with_alpha, 'cmocean_' + cmapname, rgb.shape[0])
51+
plt.register_cmap(cmap = reg_map)
52+
53+
# Register the reversed map
54+
reg_map_r = mplc.ListedColormap(rgb_with_alpha[::-1,:], 'cmocean_' + cmapname + '_r', rgb.shape[0])
55+
plt.register_cmap(cmap = reg_map_r)
3656

3757
# make colormaps available to call
3858
locals().update(cmap_d)

0 commit comments

Comments
 (0)