How to define color on matrix figure

조회 수: 2(최근 30일)
Brook
Brook 2022년 10월 14일
편집: Walter Roberson 2022년 10월 18일
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
Jan
Jan 2022년 10월 14일
Please mention, what the problem with the current code is.

댓글을 달려면 로그인하십시오.

답변(2개)

David Goodmanson
David Goodmanson 2022년 10월 14일
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 2022년 10월 18일
편집: Walter Roberson 2022년 10월 18일
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.

Community Treasure Hunt

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

Start Hunting!

Translated by