how to extract a subset of a colormap as a new colormap in matplotlib?

后端 未结 3 1502
攒了一身酷
攒了一身酷 2020-11-27 03:35

I would like to use a colormap from matplotlib e.g. CMRmap. But I don\'t want to use the \"black\" color at the beginning and the \"white\" color at the end. I\'m interested

3条回答
  •  情歌与酒
    2020-11-27 04:09

    The staticmethod colors.LinearSegmentedColormap.from_list can be used to create new LinearSegmentedColormaps. Below, I sample the original colormap at 100 points between 0.2 and 0.8:

    cmap(np.linspace(0.2, 0.8, 100))
    

    and use these colors to generate a new colormap:

    import matplotlib.pyplot as plt
    import matplotlib.colors as colors
    import numpy as np
    
    def truncate_colormap(cmap, minval=0.0, maxval=1.0, n=100):
        new_cmap = colors.LinearSegmentedColormap.from_list(
            'trunc({n},{a:.2f},{b:.2f})'.format(n=cmap.name, a=minval, b=maxval),
            cmap(np.linspace(minval, maxval, n)))
        return new_cmap
    
    arr = np.linspace(0, 50, 100).reshape((10, 10))
    fig, ax = plt.subplots(ncols=2)
    
    cmap = plt.get_cmap('jet')
    new_cmap = truncate_colormap(cmap, 0.2, 0.8)
    ax[0].imshow(arr, interpolation='nearest', cmap=cmap)
    ax[1].imshow(arr, interpolation='nearest', cmap=new_cmap)
    plt.show()
    

    enter image description here

    The plot on the left shows the image using the original colormap (in this example, jet). The plot on the right shows the same image using new_cmap.

提交回复
热议问题