Python color map but with all zero values mapped to black

前端 未结 1 1117
暗喜
暗喜 2020-12-09 11:22

I have a square array of elements which correspond to lattice sites. Some of the elements are zero and the rest vary between 1 and about 2700. Using imshow and the OrRd colo

1条回答
  •  眼角桃花
    2020-12-09 11:59

    The colormaps of Matplotlib have a set_bad and set_under property which can be used for this. This example shows how to use the set_bad

    import matplotlib.pyplot as plt
    import numpy as np
    
    # make some data
    a = np.random.randn(10,10)
    
    # mask some 'bad' data, in your case you would have: data == 0
    a = np.ma.masked_where(a < 0.05, a)
    
    cmap = plt.cm.OrRd
    cmap.set_bad(color='black')
    
    plt.imshow(a, interpolation='none', cmap=cmap)
    

    enter image description here

    To use the set_under variant you have to add the vmin keyword to the plotting command and setting is slightly above zero (but below any other valid value):

    cmap.set_under(color='black')    
    plt.imshow(a, interpolation='none', cmap=cmap, vmin=0.0000001)
    

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