Making a custom colormap using matplotlib in python

前端 未结 2 1008
孤城傲影
孤城傲影 2020-12-06 22:05

I have an image that I\'m showing with matplotlib.

\"enter

The image is gener

相关标签:
2条回答
  • 2020-12-06 22:50

    This sounds like the seismic colormap

    You might want to force the minimum and maximum to get the middle to be white.

    0 讨论(0)
  • 2020-12-06 22:57

    There's more than one way to do this. In your case, it's easiest to use LinearSegmentedColormap.from_list and specify relative positions of colors as well as the colornames. (If you had evenly-spaced changes, you could skip the tuples and just do from_list('my cmap', ['blue', 'white', 'red']).) You'll then need to specify a manual min and max to the data (the vmin and vmax kwargs to imshow/pcolor/etc).

    As an example:

    import matplotlib.pyplot as plt
    import numpy as np
    from matplotlib.colors import LinearSegmentedColormap
    
    data = np.array(
                 [[ 0.000, 0.120, 0.043, 0.094, 0.037, 0.045],
                  [ 0.120, 0.000, 0.108, 0.107, 0.105, 0.108],
                  [ 0.043, 0.108, 0.000, 0.083, 0.043, 0.042],
                  [ 0.094, 0.107, 0.083, 0.000, 0.083, 0.089],
                  [ 0.037, 0.105, 0.043, 0.083, 0.000, 2.440],
                  [ 0.045, 0.108, 0.042, 0.089, 2.440, 0.000]])
    mask = np.tri(data.shape[0], k=-1)
    data = np.ma.masked_where(mask, data)
    
    vmax = 3.0
    cmap = LinearSegmentedColormap.from_list('mycmap', [(0 / vmax, 'blue'),
                                                        (1 / vmax, 'white'),
                                                        (3 / vmax, 'red')]
                                            )
    
    fig, ax = plt.subplots()
    im = ax.pcolor(data, cmap=cmap, vmin=0, vmax=vmax, edgecolors='black')
    cbar = fig.colorbar(im)
    
    cbar.set_ticks(range(4)) # Integer colorbar tick locations
    ax.set(frame_on=False, aspect=1, xticks=[], yticks=[])
    ax.invert_yaxis()
    
    plt.show()
    

    enter image description here

    0 讨论(0)
提交回复
热议问题