Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
388 views
in Technique[技术] by (71.8m points)

python - How to redefine a color for a specific value in a matplotlib colormap

I want to use the colormap rainbow in an image using imshow. It works perfectly, but I want to redefine the color for the value 0. Instead of violete, I want to use white.

I want to do this only for the value zero, all other values can stay with the default values in the colormap.

Any idea how to do this without having to edit the colormap manually?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can also use set_under which I think makes more semantic sense than using set_bad

my_cmap = matplotlib.cm.get_cmap('rainbow')
my_cmap.set_under('w')
imshow(np.arange(25).reshape(5, 5),
       interpolation='none',
       cmap=my_cmap,
       vmin=.001)

You can tweak the colorbar to also show the 'under' (and the symmetric 'over') color using the kwarg extend, see example and docs.

For an answer to a duplicate with more complete examples see How to create matplotlib colormap that treats one value specially?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...