简体   繁体   English

Matplotlib python在colormap中更改单色

[英]Matplotlib python change single color in colormap

I use the colormap in python to plot and analyse values in a matrix. 我使用python中的colormap来绘制和分析矩阵中的值。 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. 我需要将白色与每个等于0.0的元素相关联,而对于其他元素,我想要一个“传统的”色彩图。 Looking at Python Matplotlib Colormap I modified the dictionary used by pcolor as: 看看Python Matplotlib Colormap我修改了pcolor使用的字典:

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: 结果是: 在此输入图像描述

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. 但是你可以看到它们都与白色相关联,即使我将0.00000000001设置为蓝色的起点。 How is this possible? 这怎么可能? How can I change it in order to obtain what I'd like? 我怎样才能改变它以获得我想要的东西?

Although not ideal, masking the zero value works. 虽然不理想,但屏蔽零值有效。 You can control the display of it with the cmap.set_bad() . 您可以使用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)

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM