Python – How to generate a new rainbow colormap using matplotlib

colorsmatplotlibpython

I need to plot an image filled with geophysical values ranging from 0.0 to 1.0 using a rainbow colormap.

I tried the existing rainbow colormap from matplotlib but I am not fully satisfied with it:

from matplotlib import pyplot as plt
import numpy as np

plt.pcolor(np.random.rand(10,10),cmap='rainbow')
plt.colorbar()
plt.show()

How do I create a colormap that ranges from black for a value of 0.0 and then gradually shows the following colors: violet, blue, cyan, green, yellow and finally red for a value of 1.0?

Best Answer

I used matplotlib.colors.LinearSegmentedColormap as suggested in cookbook matplotlib.

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

cdict = {'red': ((0.0, 0.0, 0.0),
                 (0.1, 0.5, 0.5),
                 (0.2, 0.0, 0.0),
                 (0.4, 0.2, 0.2),
                 (0.6, 0.0, 0.0),
                 (0.8, 1.0, 1.0),
                 (1.0, 1.0, 1.0)),
        'green':((0.0, 0.0, 0.0),
                 (0.1, 0.0, 0.0),
                 (0.2, 0.0, 0.0),
                 (0.4, 1.0, 1.0),
                 (0.6, 1.0, 1.0),
                 (0.8, 1.0, 1.0),
                 (1.0, 0.0, 0.0)),
        'blue': ((0.0, 0.0, 0.0),
                 (0.1, 0.5, 0.5),
                 (0.2, 1.0, 1.0),
                 (0.4, 1.0, 1.0),
                 (0.6, 0.0, 0.0),
                 (0.8, 0.0, 0.0),
                 (1.0, 0.0, 0.0))}

my_cmap = matplotlib.colors.LinearSegmentedColormap('my_colormap',cdict,256)
plt.pcolor(np.random.rand(10,10),cmap=my_cmap)
plt.colorbar()
plt.show()

enter image description here