Changing the transparency of patches based on their value

59 Views Asked by At

I have a matrix containing integers ranging from 0 to 20. The regions with the same integer are formed in a quite random fashion. I want to color code each integer with a different degree of grayscale. So for example, for regions with 0, I want them to be white, then for regions with 1, 5% transparency of black, for regions with 2, 10% transparency of black,..., for regions with 20, totally black.

I've tried to get the coordinates of each region, but that does not seem to be efficient for my matrix.

How can I change the transparency of my regions based on their value?

1

There are 1 best solutions below

0
Adriaan On

You can use surface() with its FaceAlpha name-value pair. It only accepts scalars though, so you'll have to plot each of your patches separately, something along the lines of:

% Create a random matrix with values 1 - 20 for plotting
my_matrix = ceil(20* rand(30));
% Build its x and y grids
[x, y] = meshgrid(1:30, 1:30);

% Open and hold the figure
figure;
hold on
for ii = unique(my_matrix)
    % Create a mask for the current value
    temp_colour = nan(size(my_matrix));
    temp_colour(my_matrix == ii) = 1;
    surface(x, y, ones(size(my_matrix)), ...
            temp_colour, ...
            'EdgeColor', 'none', ...
            'FaceAlpha', 1 - ii/max(my_matrix, 'all'))
    colormap(gray)
end 

Results in, on my R2007b,

enter image description here

If you're good with just a gray-scale image, rather than true transparency, you can simply use imagesc(my_matrix); colormap(gray).