python - Matplotlib python 在颜色图中更改单一颜色

标签 python matrix matplotlib color-mapping

我使用 python 中的颜色图来绘制和分析矩阵中的值。我需要将白色与等于 0.0 的每个元素相关联,而对于其他元素,我想要一个“传统”颜色映射。看着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))}

结果是:enter image description here

我设置:

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

但如您所见,它们都与白色相关联,即使我将 0.00000000001 设置为蓝色的起点也是如此。这怎么可能?我怎样才能改变它以获得我想要的东西?

最佳答案

虽然不理想,但屏蔽零值是可行的。您可以使用 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

关于python - Matplotlib python 在颜色图中更改单一颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16152052/

相关文章:

matlab - 设计一个简单的矩阵来对矩阵中的值进行分组

c - 在函数中保存和打印另一个文件中的矩阵

algorithm - 我如何将 IF 语句应用于矩阵的所有行(Matlab)

python - 将两位数整数转换为python列表中的一位数?

python - matplotlib 中的向下箭头符号

python - 使用 MatplotLib Python 实现革命

python - 在 matplotlib patchcollection 中设置颜色范围

python - 1064, “You have an error in your SQL syntax” 插入 MySql

python - 从 python 访问 Bloomberg API

python - 如果其中一个键的值在字符串中,则返回字典键