【3.7.4】matplotlib-cmap-将为0的值的颜色设为black

如下图所示,我需要将数值为0的颜色设置为black

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)

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)

参考资料

https://stackoverflow.com/questions/22548813/python-color-map-but-with-all-zero-values-mapped-to-black

这里是一个广告位,,感兴趣的都可以发邮件聊聊:tiehan@sina.cn
个人公众号,比较懒,很少更新,可以在上面提问题,如果回复不及时,可发邮件给我: tiehan@sina.cn