11

How to implement python matplotlib heatmap colorbar like this?

enter image description here

plt.imshow(a,aspect='auto', cmap=plt.cm.gist_rainbow_r)
plt.colorbar()
Nic3500
  • 8,144
  • 10
  • 29
  • 40
李宏强
  • 113
  • 1
  • 1
  • 4
  • I think the color map which you need is not `gist_rainbow_r` but `rainbow_r`. Refer this link for more details: https://matplotlib.org/examples/color/colormaps_reference.html. Let me know if that's what you needed. – Sheldore Jul 30 '18 at 20:11

1 Answers1

22

This example from the matplotlib gallery shows some different ways to make custom colormaps, including transparency: https://matplotlib.org/examples/pylab_examples/custom_cmap.html

In your case, it looks like you want a modified version of the gist_rainbow colormap. You can achieve this by modifying the alpha channel as follows:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

# get colormap
ncolors = 256
color_array = plt.get_cmap('gist_rainbow')(range(ncolors))

# change alpha values
color_array[:,-1] = np.linspace(1.0,0.0,ncolors)

# create a colormap object
map_object = LinearSegmentedColormap.from_list(name='rainbow_alpha',colors=color_array)

# register this new colormap with matplotlib
plt.register_cmap(cmap=map_object)

# show some example data
f,ax = plt.subplots()
h = ax.imshow(np.random.rand(100,100),cmap='rainbow_alpha')
plt.colorbar(mappable=h)
dtward
  • 799
  • 6
  • 7
  • 6
    thank you!!!!I have done this work ############ import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import LinearSegmentedColormap # get colormap ncolors = 256 color_array = plt.get_cmap('gist_rainbow_r')(range(ncolors)) # change alpha values color_array[:,-1] = np.linspace(0.0,1.0,ncolors) – 李宏强 Aug 03 '18 at 00:37
  • Seems like reverting `np.linspace(1.0, 0.0, ncolors) -> np.linspace(0.0, 1.0, ncolors)` is essential to make it work as was suggested in the comments by @李宏强. – vdi Jul 26 '22 at 06:15