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

matrix - Matplotlib python change single color in colormap

I use the colormap in python to plot and analyse values in a matrix. I need to associate the white color to each element equal to 0.0 while for others I'd like to have a "traditional" color map. Looking at Python Matplotlib Colormap I modified the dictionary used by pcolor as:

dic = {'red': ((0., 1, 1), 
               (0.00000000001, 0, 0), 
               (0.66, 1, 1), 
               (0.89,1, 1), 
               (1, 0.5, 0.5)), 
       'green': ((0., 1, 1), 
                (0.00000000001, 0, 0), 
                (0.375,1, 1), 
                (0.64,1, 1), 
                (0.91,0,0), 
                (1, 0, 0)), 
       'blue': ((0., 1, 1), 
               (0.00000000001, 1, 1), 
               (0.34, 1, 1), 
               (0.65,0, 0), 
               (1, 0, 0))}

The result is:enter image description here

I set:

matrix[0][0]=0 matrix[0][1]=0.002

But as you can see they are both associated with the white color, even if I set 0.00000000001 as the starting point for the blue. How is this possible? How can I change it in order to obtain what I'd like?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Although not ideal, masking the zero value works. You can control the display of it with the cmap.set_bad().

from matplotlib.colors import LinearSegmentedColormap
import matplotlib.pyplot as plt
import numpy as np

dic = {'red': ((0., 1, 0), 
               (0.66, 1, 1), 
               (0.89,1, 1), 
               (1, 0.5, 0.5)), 
       'green': ((0., 1, 0), 
                (0.375,1, 1), 
                (0.64,1, 1), 
                (0.91,0,0), 
                (1, 0, 0)), 
       'blue': ((0., 1, 1), 
               (0.34, 1, 1), 
               (0.65,0, 0), 
               (1, 0, 0))}

a = np.random.rand(10,10)
a[0,:2] = 0
a[0,2:4] = 0.0001

fig, ax = plt.subplots(1,1, figsize=(6,6))

cmap = LinearSegmentedColormap('custom_cmap', dic)
cmap.set_bad('white')

ax.imshow(np.ma.masked_values(a, 0), interpolation='none', cmap=cmap)

enter image description here


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

...