当使用imagesc可视化包含NaN值的数据时,Matlab将它们视为最小值(灰色表示它们是黑色,喷射蓝色等)。 jet colormap既不包含黑色也不包含白色。是否可以将nan值显示为黑/白? 例如:
data = [0 0 0 ; .5 .5 .5 ;1 1 1;nan nan nan];
应该产生蓝绿红黑条。
由于
答案 0 :(得分:9)
我编写了一个自定义函数,将NaN
值显示为透明,即alpha值为0.
function h = imagesc2 ( img_data )
% a wrapper for imagesc, with some formatting going on for nans
% plotting data. Removing and scaling axes (this is for image plotting)
h = imagesc(img_data);
axis image off
% setting alpha values
if ndims( img_data ) == 2
set(h, 'AlphaData', ~isnan(img_data))
elseif ndims( img_data ) == 3
set(h, 'AlphaData', ~isnan(img_data(:, :, 1)))
end
if nargout < 1
clear h
end
NaN
因此将显示与图形背景颜色相同的颜色。如果删除行axis image off
,则NaN
将显示与轴背景颜色相同的颜色。该函数假定输入图像的大小为n x m
(单通道)或n x m x 3
(三个通道),因此根据您的使用情况可能需要进行一些修改。
使用您的数据:
data = [0 0 0 ; .5 .5 .5 ;1 1 1;nan nan nan];
imagesc2(data);
axis on
set(gca, 'Color', [0, 0, 0])
答案 1 :(得分:1)
function imagescnan(IM)
% function imagescnan(IM)
% -- to display NaNs in imagesc as white/black
% white
nanjet = [ 1,1,1; jet ];
nanjetLen = length(nanjet);
pctDataSlotStart = 2/nanjetLen;
pctDataSlotEnd = 1;
pctCmRange = pctDataSlotEnd - pctDataSlotStart;
dmin = nanmin(IM(:));
dmax = nanmax(IM(:));
dRange = dmax - dmin; % data range, excluding NaN
cLimRange = dRange / pctCmRange;
cmin = dmin - (pctDataSlotStart * cLimRange);
cmax = dmax;
imagesc(IM);
set(gcf,'colormap',nanjet);
caxis([cmin cmax]);
答案 2 :(得分:0)
我可以看到两种可能的方法来实现这一目标:
a)修改jet colormap,使其最小值为黑色或白色,例如:
cmap = jet;
cmap = [ 0 0 0 ; cmap ]; % Add black as the first color
缺点是,如果您使用此色彩图显示没有nan
值的数据,则最小值也会以黑/白显示。
b)使用文件交换中的sc,将imagesc
绘图呈现为RGB图像。这更灵活,因为一旦你拥有RGB图像,你可以随意操纵它,包括改变所有nan
值。 e.g:
im = sc(myData);
im(repmat(isnan(myData), [ 1 1 3 ]) ) = 0; % Set all the nan values in all three
% color channels to zero (i.e. black)