Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change the intensity of a colormap in matplotlib?

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.

like image 232
Franck Dernoncourt Avatar asked May 30 '16 04:05

Franck Dernoncourt


2 Answers

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

like image 198
Bart Avatar answered Sep 29 '22 17:09

Bart


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

like image 36
Serenity Avatar answered Sep 29 '22 16:09

Serenity