2016-05-30 6 views
2

J'utilise matplotlib.pyplot.pcolor() pour tracer un heatmap avec matplotlib:Comment puis-je modifier l'intensité d'une palette de couleurs dans 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

Comment puis-je changer l'intensité de la 'RdBu' colormap? Par exemple, si la couleur est (0, 0, 1), elle devrait être transformée en (0, 0, 0.8). Plus généralement, si la couleur est (x, y, z), il devrait être transformé en (ax, ay, az), où a est un scalaire entre zéro et un.

Répondre

5

C'est tout à fait similaire à Stanley R (edit: maintenant Serenity) réponse, sans (à mon avis) la complexité inutile des boucles, annexant aux listes, et ainsi de suite:

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

2

Vous devez assembler une nouvelle carte de couleurs personnalisée basée sur une norme.

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