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

后端 未结 3 1514
攒了一身酷
攒了一身酷 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:23

    Here is an adaptation of a previous answer which embeds the plotting function:

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

    visual of output from truncate_colormap():

    Having a compact function with the plotting embedded is helpful if you need to call the function more than once.

提交回复
热议问题