Clear Filters
Clear Filters

Assigning black color to zero values of "imagesc" plot

47 views (last 30 days)
I want to use "imagesc" to plot the following matrix:
A=[9 24 6 12 6;
0 33 24 0 12;
0 0 13 14 12;
0 0 0 0 0];
I want to assign black color to 0 values and set the color bar from 6 to 33.

Accepted Answer

Image Analyst
Image Analyst on 24 Sep 2013
Try this:
A=[9 24 6 12 6;
0 33 24 0 12;
0 0 13 14 12;
0 0 0 0 0];
imagesc(A);
cmap = jet(max(A(:)));
% Make values 0-5 black:
cmap(1:6,:) = zeros(6,3);
colormap(cmap);
colorbar
  2 Comments
Ronaldo
Ronaldo on 24 Sep 2013
Edited: Ronaldo on 24 Sep 2013
It is working perfectly. Only to complete the question I ask the following question.
I adjust the color of colorbar by writing the following lines:
caxis([cmin cmax]);
h = colorbar;
set(get(h,'child'),'YData',[cmin cmax])
If the difference between the maximum and the minimum non-zero value is small (for instance 2), then the colorbar does not cover a range of color from blue to red. How can I get a range blue to red for the following matrix
A=[9 9.1 8.3 0 0;
0 9.5 8.4 0 0;
0 0 9.6 8.3 8.1;
0 0 0 9.7 0];
imagesc(A);
cmap = jet(max(A(:)));
% Make values 0-5 black:
cmap(1:6,:) = zeros(6,3);
colormap(cmap);
colorbar
Image Analyst
Image Analyst on 25 Sep 2013
A=[9 9.1 8.3 0 0;
0 9.5 8.4 0 0;
0 0 9.6 8.3 8.1;
0 0 0 9.7 0];
lowestValue = min(A(A(:)>0))
highestValue = max(A(:))
imagesc(A);
cmap = jet(256);
colormap(cmap);
caxis(gca,[lowestValue-2/256, highestValue]);
% Make less than lowest value black:
cmap(1,:)=[0,0,0];
colormap(cmap)
colorbar

Sign in to comment.

More Answers (1)

Kelly Kearney
Kelly Kearney on 24 Sep 2013
It'll be a little tricky to do with imagesc, but you could get a similar result with pcolor:
aplt = nan(size(A)+1);
aplt(1:end-1,1:end-1) = A;
aplt(aplt == 0) = NaN;
pcolor(aplt);
colorbar;
set(gca, 'color', 'k', 'clim', [6 33], 'ydir', 'reverse')
  2 Comments
Ronaldo
Ronaldo on 24 Sep 2013
Really appreciated for your quick response. The only problem which remains is the "pcolor" plot is pixelate. I need a plot similar to "imagesc" which is smooth.
Kelly Kearney
Kelly Kearney on 25 Sep 2013
Neither function does any smoothing, unless you use interpolated shading with the pcolor plot. If you're referring to the black outlines of each grid cell that is the default under pcolor, you can alter that with a simple
shading flat;

Sign in to comment.

Categories

Find more on Colormaps in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!