IndexError Exception with matplotlib custom colormap/LinearSegmentedColormap

时间:2016-10-20 19:51:25

标签: python matplotlib

I am trying to create a custom color table in matplotlib, yet am encountering a problem. I already have a list of colors with r,g,b,a values between 0 and 1. However, It seems I am not constructing it properly to be used in a LinearSegmentedColormap.

Here is the code I am using to construct it.

while len(iterator) != 0:
    element = iterator.pop()
    if element.get('r') != None:
        r = np.float64(element.get('r'))
        g = np.float64(element.get('g'))
        b = np.float64(element.get('b'))
        a = np.float64(element.get('a'))
        vals = np.array([r,g,b,a])          
        cmapList.append(vals)
cmapList = np.array(cmapList)
colorMap = LinearSegmentedColormap("name",cmapList,len(cmapList),gamma = 1.0)

However, when I try to use the colormap in a plot or call the colormap

colorMap(1)

I receive this error.

Traceback (most recent call last):
  File "satelliteVisFwz.py", line 63, in <module>
    colorTable(1)
  File "/awips2/python/lib/python2.7/site-packages/matplotlib/colors.py", line 553, in __call__
    self._init()
  File "/awips2/python/lib/python2.7/site-packages/matplotlib/colors.py", line 732, in _init
    self.N, self._segmentdata['red'], self._gamma)
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

1 个答案:

答案 0 :(得分:0)

I just realized you have to use the static method from_list

so

LinearSegmentedColormap.from_list("name",cmapList,len(cmapList),gamma=1.0)

gave the wanted result.