Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

arrays - Python color map but with all zero values mapped to black

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 colour map, I want all lattice sites greater than 0 to display the corresponding colour but importantly, all sites with value 0 to be displayed as black. I have tried defining a new color map as follows:

colors = [(0,0,0)] + [(pylab.cm.OrRd(i)) for i in range(1,256)] 
new_map = matplotlib.colors.LinearSegmentedColormap.from_list('new_map', colors, N=256)

but the range of values in my array is too large and so a lot of non-zero values get displayed as black.

Many thanks.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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

# for mpl 3.3 and higher use
cmap = mpl.cm.get_cmap("OrRd").copy()

cmap.set_bad(color='black')

im = 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')    
im = plt.imshow(a, interpolation='none', cmap=cmap, vmin=0.0000001)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...