自定义matplotlib cmaps

ato*_*3ls 1 python plot numpy matplotlib

我在形状数组(12,1)中有一些标准化的直方图数据:

>>> hnorm

   array([[ 0.        ],
       [ 0.        ],
       [ 0.01183432],
       [ 0.0295858 ],
       [ 0.04142012],
       [ 0.04142012],
       [ 0.03550296],
       [ 0.01775148],
       [ 1.        ],
       [ 0.98816568],
       [ 0.56213018],
       [ 0.        ]])
Run Code Online (Sandbox Code Playgroud)

我想用'热图'样式来绘制它.我是这样做的:

import matplotlib.pyplot as plt
plt.imshow(hnorm, cmap='RdBu',origin='lower')
Run Code Online (Sandbox Code Playgroud)

这有效(除了轴格式).

在此输入图像描述

但是,我想自定义色彩图从淡白色变为红色.我试过了:

import matplotlib.colors as col

cdict = {'red': ((0.00, 0.07, 0.14),
        (0.21, 0.28, 0.35),
        (0.42, 0.49, 0.56),
        (0.63, 0.70, 0.77),
        (0.84, 0.91, 0.99)),
        'green': ((0.0, 0.0, 0.0),
        (0.0, 0.0, 0.0),
        (0.0, 0.0, 0.0),
        (0.0, 0.0, 0.0),
        (0.0, 0.0, 0.0)),
        'blue': ((0.0, 0.0, 0.0),
        (0.0, 0.0, 0.0),
        (0.0, 0.0, 0.0),
        (0.0, 0.0, 0.0), 
        (0.0, 0.0, 0.0))}
cmap1 = col.LinearSegmentedColormap('my_colormap',cdict,N=256,gamma=0.75)
plt.imshow(hnorm, cmap=cmap1,origin='lower')
Run Code Online (Sandbox Code Playgroud)

这失败了.我有什么想法我做错了吗?

Rut*_*ies 5

作为askewchan的cmap'Reds'建议更简单,(imo)也更好看.但我会回答只是为了说明构建自定义cmap的方法是如何工作的.

在您的颜色字​​典中,您有5个条目,您可以在其中指定颜色.由于您只想使用红色和白色,因此只需要两个内容.对于白色,必须使用由位置0.0处的颜色值1.0​​指定的所有颜色.对于红色,只应在1.0位置使用红色.

您还只为红色元组提供值(0除外).这只会在"完整"的红色和黑色之间给出不同的红色阴影(因为你总是将绿色和蓝色视为0).

cdict = {'red': ((0.0, 1.0, 1.0),
                 (1.0, 1.0, 1.0)),

        'green': ((0.0, 1.0, 1.0),
                  (1.0, 0.0, 0.0)),

        'blue': ((0.0, 1.0, 1.0),
                 (1.0, 0.0, 0.0))}

my_cmap = mpl.colors.LinearSegmentedColormap('my_colormap', cdict)

plt.imshow(np.random.rand(20,20), cmap=my_cmap, origin='lower', interpolation='none')
plt.colorbar(shrink=.75)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

另一个示例显示了两个颜色项如何允许在cmap中"跳转":

cdict = {'red': ((0.0, 1.0, 1.0), # full red
                 (0.5, 1.0, 0.0), # full red till, no red after
                 (1.0, 1.0, 1.0)), # full red

        'green': ((0.0, 1.0, 1.0), # full green
                  (0.5, 0.0, 0.0), # no green
                  (1.0, 1.0, 1.0)), # full green

        'blue': ((0.0, 1.0, 1.0), # full blue
                 (0.5, 0.0, 1.0), # no blue till, full blue after
                 (1.0, 1.0, 1.0))} # full blue

my_cmap = mpl.colors.LinearSegmentedColormap('my_colormap', cdict)

plt.imshow(np.random.rand(20,20), cmap=my_cmap, origin='lower', interpolation='none')
plt.colorbar(shrink=.75)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述