How to define color on matrix figure

2 views (last 30 days)
Brook
Brook on 14 Oct 2022
Edited: Walter Roberson on 18 Oct 2022
Hi everyone,
I have a 19x19 matrix and I want all the 0 values to mark with black color on the figure.
this is the code that I am using the generate my figure:
[R2, P2] = corrcoef(x_avg_cor_time2);
figure;
imagesc(R2);
colorbar;
title('x_avg_cor_time1')
Any help would be appriciated! Thanks!
  1 Comment
Jan
Jan on 14 Oct 2022
Please mention, what the problem with the current code is.

Sign in to comment.

Answers (2)

David Goodmanson
David Goodmanson on 14 Oct 2022
Hi Jan,
the following method comes up with black not just for values that are exactly zero (I don't know how likely that might be for a correlation coefficient calculation), but also for values that are near zero, with a precision that is related to the number of rows of the colormap.
n = size(colormap,1) % assuming you already have a plot up and running
b = max(R2,[],'all');
a = min(R2,[],'all');
ind = round(1+(-a/(b-a))*(n-1));
map = colormap;
map(ind,:) = [0 0 0];
figure(2)
imagesc(R2)
colormap(map)
colorbar

Walter Roberson
Walter Roberson on 18 Oct 2022
Edited: Walter Roberson on 18 Oct 2022
Create a black underlayer and make the image transparent everywhere it is 0.
[R2, P2] = corrcoef(x_avg_cor_time2);
figure;
Z = zeros(size(R2,1), size(R2,2), 3); %black background
image(Z);
hold on
alphadata = double(R2 ~= 0);
h = imagesc(R2);
h.AlphaData = alphadata;
hold off
colorbar;
title('x_avg_cor_time1')
The disadvantage is that the black will not show up in the color bar.
As @David Goodmanson discussed, when you have a color present in the colorbar, it always describes a range of data, never an exact value. You could, for example, make a colormap that had 1024 entries and set one of them to black so that the color would cover (say) +/- 0.003 -- but you cannot get a colorbar entry to match an exact value when you have continuous data.

Categories

Find more on Colormaps in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!