李宏强
李宏强

Reputation: 133

python matplotlib heatmap colorbar from transparent

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()

Upvotes: 13

Views: 18014

Answers (1)

dtward
dtward

Reputation: 869

This matplotlib documentation page shows some different ways to make custom colormaps, including transparency: https://matplotlib.org/stable/users/explain/colors/index.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.colormaps.register(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)

Above code will create a colormap rainbow_alpha that is fully opaque at start and linearly changes transparency to be fully transparent at end. If you want a reverse effect (transparent at start and opaque at end) you can change line 9 like so:

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

You can also change transparency of a single value:

 color_array[0,-1] = 0.0

Note: For matplotlib versions <3.7 colormaps were registered using plt.register_cmap

Upvotes: 28

Related Questions