Matplotlib python 更改颜色图中的单一颜色 [英] Matplotlib python change single color in colormap

查看:64
本文介绍了Matplotlib python 更改颜色图中的单一颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 python 中的颜色图来绘制和分析矩阵中的值.我需要将白色与等于0.0的每个元素相关联,而对于其他元素,我希望具有传统"颜色图.查看 Python Matplotlib Colormap 我将 pcolor 使用的字典修改为:

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))}

结果是:

我设置:

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

但是,您可以看到它们都与白色相关联,即使我将0.00000000001设置为蓝色的起点也是如此.这怎么可能?如何更改它以获得我想要的东西?

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?

推荐答案

虽然不理想,但屏蔽零值是有效的.您可以使用 cmap.set_bad() 控制它的显示.

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)

这篇关于Matplotlib python 更改颜色图中的单一颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆