8

I use matplotlib.pyplot.pcolor() to plot a heatmap with matplotlib:

import numpy as np
import matplotlib.pyplot as plt    

np.random.seed(1)
data =  np.sort(np.random.rand(8,12))
plt.figure()
c = plt.pcolor(data, edgecolors='k', linewidths=4, cmap='RdBu', vmin=0.0, vmax=1.0)
plt.colorbar(c)
plt.show()

enter image description here

How can I change the intensity of the 'RdBu' colormap? E.g., if the color is (0, 0, 1), it should be transformed into (0, 0, 0.8). More generally, if the color is (x, y, z), it should be transformed into (ax, ay, az), where a is some scalar between zero and one.

Franck Dernoncourt
  • 77,520
  • 72
  • 342
  • 501

2 Answers2

10

This is quite similar to Stanley R's (edit: now Serenity) answer, without the (in my opinion) unnecessary complexity of loops, appending to lists, et cetera:

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

a = 0.5

# Get the colormap colors, multiply them with the factor "a", and create new colormap
my_cmap = plt.cm.RdBu(np.arange(plt.cm.RdBu.N))
my_cmap[:,0:3] *= a 
my_cmap = ListedColormap(my_cmap)

np.random.seed(1)
data =  np.sort(np.random.rand(8,12))
plt.figure()
plt.subplot(121)
c = plt.pcolor(data, edgecolors='k', linewidths=4, cmap='RdBu', vmin=0.0, vmax=1.0)
plt.colorbar(c)
plt.subplot(122)
c = plt.pcolor(data, edgecolors='k', linewidths=4, cmap=my_cmap, vmin=0.0, vmax=1.0)
plt.colorbar(c)
plt.show()

enter image description here

Bart
  • 9,825
  • 5
  • 47
  • 73
2

You have to assembly new custom color map based on a standard.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm

np.random.seed(1)
data =  np.sort(np.random.rand(8,12))
plt.figure()
cmap = cm.get_cmap('RdBu', len(data)) # set how many colors you want in color map
# modify colormap
alpha = .5
colors = []
for ind in xrange(cmap.N):
    c = []
    for x in cmap(ind)[:3]: c.append(x*alpha)
    colors.append(tuple(c))
my_cmap = matplotlib.colors.ListedColormap(colors, name = 'my_name')
# plot with my new cmap
cb = plt.pcolor(data, edgecolors='k', linewidths=4, cmap=my_cmap, vmin=0.0, vmax=1.0)
plt.colorbar(cb)
plt.show()

enter image description here

Serenity
  • 35,289
  • 20
  • 120
  • 115