Reverse colormap in matplotlib

前端 未结 7 807
小蘑菇
小蘑菇 2020-11-28 02:04

I would like to know how to simply reverse the color order of a given colormap in order to use it with plot_surface.

7条回答
  •  半阙折子戏
    2020-11-28 03:03

    There are two types of LinearSegmentedColormaps. In some, the _segmentdata is given explicitly, e.g., for jet:

    >>> cm.jet._segmentdata
    {'blue': ((0.0, 0.5, 0.5), (0.11, 1, 1), (0.34, 1, 1), (0.65, 0, 0), (1, 0, 0)), 'red': ((0.0, 0, 0), (0.35, 0, 0), (0.66, 1, 1), (0.89, 1, 1), (1, 0.5, 0.5)), 'green': ((0.0, 0, 0), (0.125, 0, 0), (0.375, 1, 1), (0.64, 1, 1), (0.91, 0, 0), (1, 0, 0))}
    

    For rainbow, _segmentdata is given as follows:

    >>> cm.rainbow._segmentdata
    {'blue':  at 0x7fac32ac2b70>, 'red':  at 0x7fac32ac7840>, 'green':  at 0x7fac32ac2d08>}
    

    We can find the functions in the source of matplotlib, where they are given as

    _rainbow_data = {
            'red': gfunc[33],   # 33: lambda x: np.abs(2 * x - 0.5),
            'green': gfunc[13], # 13: lambda x: np.sin(x * np.pi),
            'blue': gfunc[10],  # 10: lambda x: np.cos(x * np.pi / 2)
    }
    

    Everything you want is already done in matplotlib, just call cm.revcmap, which reverses both types of segmentdata, so

    cm.revcmap(cm.rainbow._segmentdata)
    

    should do the job - you can simply create a new LinearSegmentData from that. In revcmap, the reversal of function based SegmentData is done with

    def _reverser(f):
        def freversed(x):
            return f(1 - x)
        return freversed
    

    while the other lists are reversed as usual

    valnew = [(1.0 - x, y1, y0) for x, y0, y1 in reversed(val)] 
    

    So actually the whole thing you want, is

    def reverse_colourmap(cmap, name = 'my_cmap_r'):
         return mpl.colors.LinearSegmentedColormap(name, cm.revcmap(cmap._segmentdata)) 
    

提交回复
热议问题