Matplotlib:ListedColormap不映射颜色

时间:2018-10-16 19:15:33

标签: python matplotlib plot

我无法理解为什么自定义cmap无法使用plt.imshow正确映射到图像。

当我在不指定cmap的情况下绘制二维数组resr时,我看到:

resr = np.array([[0,2],[3,4]],dtype=int)
plt.imshow(resr)

enter image description here

这看起来不错。当我尝试使用以下方式传递我指定颜色的cmap时:

cmap1 = ['#7fc97f', '#ffff99', '#386cb0', '#f0027f']
cmap = colors.ListedColormap(cmap1) 
plt.imshow(resr, cmap=cmap)

我知道:

enter image description here

由于某种原因,颜色cmap1[3]被映射到resr34上。为什么会这样?

2 个答案:

答案 0 :(得分:1)

我在这里看到两个选项:

A。将数据映射到类别

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.colors as colors
from mpl_toolkits.axes_grid1 import make_axes_locatable

resr = np.array([[0,2],[3,4]],dtype=int)
u, ind = np.unique(resr, return_inverse=True)
norm = colors.BoundaryNorm(np.arange(len(u)+1)-.5, len(u))
cmap1 = ['#7fc97f', '#ffff99', '#386cb0', '#f0027f']
cmap = colors.ListedColormap(cmap1) 

fig,ax = plt.subplots()
im = ax.imshow(ind.reshape(resr.shape), cmap=cmap,norm=norm)
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%")

cb = plt.colorbar(im, cmap=cmap,norm=norm,cax=cax)

cb.set_ticks(np.arange(len(u)))
cb.ax.set_yticklabels(cmap1)
cb.ax.tick_params(labelsize=10)

plt.show()

B。将类别映射到数据

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.colors as colors
from mpl_toolkits.axes_grid1 import make_axes_locatable

resr = np.array([[0,2],[3,4]],dtype=int)

u = np.unique(resr)
bounds = np.concatenate(([resr.min()-1], u[:-1]+np.diff(u)/2. ,[resr.max()+1]))
print(bounds)
norm = colors.BoundaryNorm(bounds, len(bounds)-1)
cmap1 = ['#7fc97f', '#ffff99', '#386cb0', '#f0027f']
cmap = colors.ListedColormap(cmap1) 

fig,ax = plt.subplots()
im = ax.imshow(resr, cmap=cmap,norm=norm)
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%")

cb = plt.colorbar(im, cmap=cmap,norm=norm,cax=cax)

cb.set_ticks(bounds[:-1]+np.diff(bounds)/2.)
cb.ax.set_yticklabels(cmap1)
cb.ax.tick_params(labelsize=10)

plt.show()

两种情况的结果都是相同的。

enter image description here

答案 1 :(得分:0)

在@ImportanceOfBeingErnest的评论中提供了指向他们的post的链接之后,我找到了解决方案。

诀窍是使用np.unique(resr)BoundaryNorm的通行证。像这样:

resr = np.array([[0,2],[3,4]],dtype=int)

norm = colors.BoundaryNorm(np.unique(resr), len(np.unique(resr))-1)
cmap1 = ['#7fc97f', '#ffff99', '#386cb0', '#f0027f']
cmap = colors.ListedColormap(cmap1) 
plt.imshow(resr, cmap=cmap,norm=norm);plt.colorbar()

哪个返回预期结果:

enter image description here