1

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?

jmb_louis
  • 1,055
  • 2
  • 13
  • 15
  • possible duplicate of [Create own colormap using matplotlib and plot color scale](http://stackoverflow.com/questions/16834861/create-own-colormap-using-matplotlib-and-plot-color-scale) – pseudocubic Sep 17 '14 at 13:19

1 Answers1

6

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

tom10
  • 67,082
  • 10
  • 127
  • 137
jmb_louis
  • 1,055
  • 2
  • 13
  • 15
  • thanks for the edit, I didn't had enough reputation to post an image at the time I posted the answer! – jmb_louis Sep 17 '14 at 14:25
  • 1
    Another option that may work for you is to use a standard colormap with `set_under`, as done here: https://stackoverflow.com/questions/25432654/how-to-create-matplotlib-colormap-that-treats-one-value-specially In your usage the black is continuous with the colormap and with `set_under` it's not. – tom10 Sep 17 '14 at 14:48
  • yes thanks but I also need the other colors (e.g. yellow, cyan) that are not available in the original rainbow colormap. – jmb_louis Sep 17 '14 at 15:48