matplotlib:不连续整数的颜色条映射

时间:2018-10-22 14:27:35

标签: python matplotlib plot colorbar

我有一个项目,试图绘制2D整数类型的数组。值可以在0到4之间变化,并且可能不全都存在。

我开始用整数数组resr,列出的色彩图cmapcolormap index based on discrete intervals norm开发绘图例程:

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)

norm = colors.BoundaryNorm(np.unique(resr), len(np.unique(resr))-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%")
bounds = 0.5+np.arange(norm.N+1)
cb = plt.colorbar(im, cmap=cmap,norm=norm,boundaries=bounds,cax=cax)
tic_locs =1+np.arange(norm.N+1)
cb.set_ticks(tic_locs)
cb.ax.set_yticklabels(cmap1)
cb.ax.tick_params(labelsize=10)

哪个返回预期结果:

enter image description here

当我更改resr进行测试以确保绘图例程在其他情况下仍然有效时:

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

图像正确绘制,但颜色栏的格式不正确:

enter image description here

为什么会这样?

0 个答案:

没有答案