本文介绍了Matplotlib:ListedColormap 不映射颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我无法理解为什么自定义 cmap
没有正确映射到使用 plt.imshow
的图像.
I am having trouble understanding why a custom cmap
is not being properly mapped to an image using plt.imshow
.
当我在不指定cmap的情况下绘制二维数组 resr
时,我会看到:
When I plot the 2-D array resr
without specifying a cmap, I see:
resr = np.array([[0,2],[3,4]],dtype=int)
plt.imshow(resr)
这看起来是对的.当我尝试使用以下方法传递我指定颜色的 cmap 时:
This looks right. When I try and pass a cmap of my specified colors using:
cmap1 = ['#7fc97f', '#ffff99', '#386cb0', '#f0027f']
cmap = colors.ListedColormap(cmap1)
plt.imshow(resr, cmap=cmap)
我明白了:
由于某种原因,颜色 cmap1 [3]
被映射到 resr
值 3
和 4
.为什么会这样?
For some reason, the color cmap1[3]
is being mapped to the resr
values 3
and 4
. Why is this happening?
推荐答案
我在这里看到两个选项:
I see two options here:
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()
两种情况的结果相同.
这篇关于Matplotlib:ListedColormap 不映射颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!