Search code examples
matlabplotmatlab-figurecolormap

How to create a colormap based on value?


I have two vectors as follows:

x = 0:5:50;
sir_dB = [50 20 10 5 2 0 -5 -10 -20 -20 -20] 

Where x denotes the distance on the x-axis and sir_dB the SNR. For this, I need to generate a color map for a grid of 50 x 60m something similar to this:

enter image description here

based on the value of sir_dB.

I tried the following:

sir_dB = [50 20 10 5 2 0 -5 -10 -20 -20 -20];
xrange = 0:50;
yrange = -30:30;
% create candidate set
[X, Y] = ndgrid(xrange, yrange); % grid of points with a spacing of 1. 
candidate_set = [X(:), Y(:)];
test_pt = [0 30];
radius = 5;
% find which of these are within the radius of selected point:
idx = rangesearch(candidate_set, test_pt, radius ); 
neighborhood = candidate_set(idx{1}, :);

Once I have the neighbors at a radius of 5m, I need to color that part of the grid based on the sir_dB value for a corresponding x value.

I need to have the plot in such a way that for all values of sir_dB greater than 15, the grid should be colored green, yellow for y greater than 0 and red for y greater than -20.

Could someone provide me inputs of how to do this best?


Solution

  • Im not sure exactly what you want, but this should get you started with contourf. I increased the granularity of xrange and yrange to make the radius more smooth but you can change it back if you want.

    x = 0:5:50;
    sir_dB = [50 20 10 5 2 0 -5 -10 -20 -20 -20];
    xrange = 0:0.1:50;
    yrange = -30:0.1:30;
    % create candidate set
    [X, Y] = ndgrid(xrange, yrange); % grid of points with a spacing of 1.
    candidate_set = [X(:), Y(:)];
    
    test_pt = [0 30];
    r = sqrt((test_pt(1)-X(:)).^2 + (test_pt(2)-Y(:)).^2);
    idx = r>5;
    snr = nan(size(X));
    snr(idx) = interp1(x,sir_dB,X(idx),'linear');
    
    % Some red, yellow, green colors
    cmap = [0.8500    0.3250    0.0980;
            0.9290    0.6940    0.1250;
            0         0.7470    0.1245];
    
    figure();
    colormap(cmap);
    contourf(X,Y,snr,[-20,0,15],'LineStyle','none');
    

    Plotting the the contour plot alongside the original sir_dB we see that it lines up (assuming you want linear interpolation). If you don't want linear interpolation use 'prev' or 'next' for the interp1 method.

    figure();
    colormap(cmap);
    subplot(2,1,1);
    contourf(X,Y,snr,[-20,0,15],'LineStyle','none');
    subplot(2,1,2);
    plot([0,50],[-20,-20],'-r',[0,50],[0,0],'-y',[0,50],[15,15],'-g',x,sir_dB);
    

    enter image description here