离散色图无法正常工作?

2 投票
1 回答
3718 浏览
提问于 2025-04-18 17:18

我有一组从0到大约450的数值,我想制作一个离散的颜色图,这样一段数值总是用特定的颜色来表示。

我定义颜色的方式是这样的:

red = np.array([0, 0, 221, 239, 235, 248, 239, 234, 228, 222, 205, 196, 161, 147, 126, 99, 87, 70, 61]) / 256.
green = np.array([16, 217, 242, 240, 255, 225, 190, 160, 128, 87, 72, 59, 33, 21, 29, 30, 30, 29, 26]) / 256.
blue = np.array([255, 255, 243, 82, 11, 1, 63, 37, 39, 21, 27, 23, 22, 26, 29, 28, 27, 25, 22]) / 256.
colors = np.array([red, green, blue]).T

cmap = mpl.colors.ListedColormap(colors)
bounds = np.arange(0,450,23) # as I understand need to be num colors + 1
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)

plot = iplt.contourf(to_plot, red.size, cmap=cmap)\
# as many contours as there are colours

根据上面的内容,如果我理解得没错,第一个颜色(深蓝色)应该对应0到23的数值范围。但是我看到的是:

enter image description here

在这个图上,0到23的范围没有出现,所以深蓝色也不应该出现,但它却出现了?我哪里做错了?

编辑:这是我添加norm参数后发生的情况:

enter image description here 这时候颜色区间搞乱了?

最终编辑:现在可以用了,这是我做的:

#No changes here:
new_cols = np.load(os.path.expanduser('~/Desktop/dl/colormap.npy'))
new_cmap = mpl.colors.ListedColormap(new_cols)
new_bounds = np.linspace(0,420,21)
new_norm = mpl.colors.BoundaryNorm(new_bounds,new_cmap.N)
plot = iplt.contourf(to_plot, 20, cmap=new_cmap, norm=new_norm)

#This is different:
cax, kw = mpl.colorbar.make_axes(ax, orientation='horizontal')
cbar = mpl.colorbar.ColorbarBase(cax, cmap=new_cmap, norm=new_norm,
spacing='proportional', ticks=new_bounds, boundaries=new_bounds, format='%1i', **kw)

注意,颜色条中的mappable参数已经去掉了。因为我把它映射到一个在norm范围内没有值的图像上,所以它把我的颜色条重新缩放以适应这个图像。现在上面的内容可以正常工作了。我也稍微改了一下颜色方案,所以不要被不同的颜色搞混了 :).

enter image description here

1 个回答

1

(更新:clim)

让我们来做一个更简单的例子:

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.colors

# create very simple image data
img = np.linspace(-1.9,1.9,100).reshape(1,-1)

# create a very simple color palette
colors = [[1,.5,.5], [1,0,0], [0,1,0], [0,0,1], [0,0,0], [0, .5, .5]]
cm = matplotlib.colors.ListedColormap(colors)
norm = matplotlib.colors.BoundaryNorm([-3,-2,-1,0,1,2,2], cm.N)

# draw the image
f = plt.figure()
ax = f.add_subplot(111)
im = ax.imshow(img, extent=[-1.9,1.9,0,1], cmap=cm, norm=norm)
im.set_clim(-3, 3)

# draw the color bar
plt.colorbar(im)

这样做会得到:

在这里输入图片描述

所以,如果你按照GWW在评论中建议的做法(添加norm=norm这个参数),你的代码几乎没有什么问题。如果你想显示整个颜色条,你需要为图像设置clim

撰写回答