也许那里有更好的解决方案,但我可以在这里提出一个。本质上,我正在创建图像的 RGB 表示来显示它。所以我选择了一个包含我最初想要的颜色数量的颜色图。然后,从数据中,将它们转换为索引并用于in2rgb()
获取 RGB 图像。然后,我可以获取每种颜色的 bin 大小并适当地标记颜色条。
% Randomly generate some data for demonstration
A = [1 nan nan; 1 2 3; 4 5 6];
B = [nan 0 nan; 4 3 2; 1 2 1];
C = (A - B) ./ ((A + B) ./ 2);
% Number of colors you want to use
ncolor = 8;
data_colormap = [jet(ncolor); 1 1 1; 0 0 0; 0.5 0.5 0.5];
data_range = [min(C(:)) max(C(:))];
data_ind = (C - data_range(1)) / (data_range(2) - data_range(1)) * (ncolor - 1) + 1;
% Assign indices > ncolor for the special cases
data_ind(isnan(A)) = ncolor + 1; % isnan(A) assign to white
data_ind(isnan(B)) = ncolor + 2; % isnan(A) assign to black
data_ind(isnan(A) & isnan(B)) = ncolor + 3; % isnan(A) + isnan(B)
% Get the RGB representation
img = ind2rgb(round(data_ind), data_colormap);
imagesc(img)
% Custom labels for the colorbar
bin_size = (data_range(2)-data_range(1)) / ncolor;
caxis([data_range(1) data_range(2) + 3*bin_size])
colormap(data_colormap)
ax = colorbar;
yticks = get(ax, 'YTick');
yticks = yticks(yticks < data_range(2));
yticklabels = num2cell(yticks);
% Pad another 3 custom labels
yticks = [yticks, data_range(2)+[bin_size 2*bin_size 3*bin_size]-0.5*bin_size];
yticklabels = [yticklabels 'isnan(A)', 'isnan(B)', 'both'];
set(ax, 'YTick', yticks, 'YTickLabel', yticklabels)