在matplotlib中自定义colorbar

时间:2012-08-22 12:35:41

标签: python matplotlib

我有一个我正在用imshow绘图的2D数组,我想要根据我的数组的每个像素的值来获得costum颜色。我将用一个例子来解释它。

from pylab import *
from numpy import *

img = ones((5,5))
img[1][1] = 2

imshow(img,interpolation='nearest');colorbar()

如果您运行此代码,您会在蓝色背景中看到一个红色方块。红色方块对应于[1][1]中的像素img,而其他像素则为蓝色,因为它们的值为1.如果我希望红色方块用自定义颜色着色,该怎么办? 或者更一般地说,如果我在示例中有一个像img这样的2D数组,我怎么能用我可以选择的颜色用相同的值着色像素。

我找到了这个页面,解释了如何生成自定义颜色栏,但这没用:http://www.scipy.org/Cookbook/Matplotlib/Show_colormaps

1 个答案:

答案 0 :(得分:3)

您发送的链接具有以下内容:

  

但是,如果我认为那些色彩图很难看怎么办?好吧,只需要你的   拥有使用matplotlib.colors.LinearSegmentedColormap。首先,创建一个   将范围(0,1)映射到RGB光谱中的值的脚本。在   这本词典,每种颜色都会有一系列元组   '红色','绿色'和'蓝色'。每种颜色中的第一个元素   系列需要从0到1排序,任意间距   插图中。现在,考虑下面的“红色”系列中​​的(0.5,1.0,0.7)。   这个元组表示在(0,1)范围内的0.5处,插值来自   低于1.0,高于0.7。通常,每个中的后两个值   元组将是相同的,但使用不同的值是有帮助的   在你的色彩图中放置休息符。这比理解更容易理解   声音,正如这个简单的脚本所示:

   1 from pylab import *
   2 cdict = {'red': ((0.0, 0.0, 0.0),
   3                  (0.5, 1.0, 0.7),
   4                  (1.0, 1.0, 1.0)),
   5          'green': ((0.0, 0.0, 0.0),
   6                    (0.5, 1.0, 0.0),
   7                    (1.0, 1.0, 1.0)),
   8          'blue': ((0.0, 0.0, 0.0),
   9                   (0.5, 1.0, 0.0),
  10                   (1.0, 0.5, 1.0))}
  11 my_cmap = matplotlib.colors.LinearSegmentedColormap('my_colormap',cdict,256)
  12 pcolor(rand(10,10),cmap=my_cmap)
  13 colorbar()

这不正是你想要的吗?

以下是如何使用您提供的图片执行此操作的示例:

import matplotlib
from matplotlib import pyplot as plt
from pylab import *

img = ones((5,5))
img[1][1] = 2

cdict = {'red': ((0.0, 0.0, 0.0),
                (0.5, 1.0, 0.7),
                     (1.0, 1.0, 1.0)),
             'green': ((0.0, 0.0, 0.0),
                       (0.5, 1.0, 0.0),
                       (1.0, 1.0, 1.0)),
             'blue': ((0.0, 0.0, 0.0),
                      (0.5, 1.0, 0.0),
                     (1.0, 0.5, 1.0))}

my_cmap = matplotlib.colors.LinearSegmentedColormap('my_colormap',cdict,256)
plt.pcolor(img,cmap=my_cmap)
plt.colorbar()
plt.show()

此外,如果您真的想要将数字映射到颜色,可以使用您链接到的示例中指定的discrete_cmap,这是scipy文档提供的示例方法:

def discrete_cmap(N=8):
    """create a colormap with N (N<15) discrete colors and register it"""
    # define individual colors as hex values
    cpool = [ '#bd2309', '#bbb12d', '#1480fa', '#14fa2f', '#000000',
              '#faf214', '#2edfea', '#ea2ec4', '#ea2e40', '#cdcdcd',
              '#577a4d', '#2e46c0', '#f59422', '#219774', '#8086d9' ]
    cmap3 = col.ListedColormap(cpool[0:N], 'indexed')
    cm.register_cmap(cmap=cmap3)