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
403 views
in Technique[技术] by (71.8m points)

python - Custom colour maps Matplotlib, make one value a prescribed colour

I have an array in python, using matplotlib, with floats ranging between 0 and 1.

I am displaying this array with imshow, I am trying to create a custom cmap, which is identical to Greens, however when a cell becomes 0 I would like to be able to map that value to red, and leave the rest of he spectrum unchanged.

If anyone more familiar with matplotlib would be able to help me I would greatly appreciate it!

For instance how would I edit this script so that the zero value in the matrix showed as red?

import numpy as np

from matplotlib import pyplot as plt

import matplotlib

x = np.array([[0,1,2],[3,4,5],[6,7,8]])

fig = plt.figure()

cmap_custom = matplotlib.cm.Greens

plt.imshow( x, interpolation='nearest' ,cmap = cmap_custom)

plt.colorbar()

plt.show()
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The colormaps in matplotlib allow you to set special colors for values that are outside of the defined range. In your case specify the color for values below the defined range with cmap_custom.set_under('r'). Then you also need to specify the lower end of the range: vmin=0.01 (just some value > 0). Finally create the colorbar with plt.colorbar(extend='min').

import numpy as np
from matplotlib import pyplot as plt
import matplotlib

x = np.array([[0,1,2],[3,4,5],[6,7,8]])

fig = plt.figure()
cmap_custom = matplotlib.cm.Greens
cmap_custom.set_under('r')
plt.imshow( x, interpolation='nearest' ,cmap = cmap_custom, vmin=0.01)
plt.colorbar(extend='min')
plt.show()

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

...