Making a static legend, independent of the actual plot

1.4k views Asked by At

I'm plotting two surfaces in Matlab, the ground level which is constant and the water level which is changing in time.

I use an if statement to change the colormap of the water with increasing depth, determined by two thresholds (in the code below the thresholds are represented by the array C)

if max(C(:)) < 2
    colormap([0.5 0.25 0 ; 0 0.8 1]);
elseif max(C(:)) >= 2 && max(C(:)) < 3
    colormap([0.5 0.25 0 ; 0 0.8 1 ; 0 0.5 0.65]);
elseif max(C(:)) >= 3
    colormap([0.5 0.25 0 ; 0 0.8 1 ; 0 0.5 0.65 ; 0 0.2 0.3]);
end

The result is that when the water level is below threshold 1 it is a light blue, between the two thresholds it turns darker, and above threshold 2 it turns darker yet.

My problem is that when I draw the legend

legend('ground','water');

... I only get one color representing the water, and it changes according to the max depth. How do I make a static legend showing all four categories with a color example:

  1. (brown) Ground
  2. (light blue) Water level beneath threshold 1
  3. (standard blue) Water level between thresholds
  4. (dark blue) Water level above threshold 2

The only solution I can think of is making 3 neat little patches somewhere by the axis (where it won't be noticed) in the right blue colors and then making the legend point at them and not the water surface. But that would be a real crappy solution...

1

There are 1 answers

1
Alex On

You can display a colorbar():

C = [1 2 3 4];

if max(C(:)) < 2
    colormap([0.5 0.25 0 ; 0 0.8 1]);
elseif max(C(:)) >= 2 && max(C(:)) < 3
    colormap([0.5 0.25 0 ; 0 0.8 1 ; 0 0.5 0.65]);
elseif max(C(:)) >= 3
    colormap([0.5 0.25 0 ; 0 0.8 1 ; 0 0.5 0.65 ; 0 0.2 0.3]);
end

% whatever to make your plot
imagesc(C);

% display a colorbar
cb_ax = colorbar;

% label it appropriately
set(cb_ax, 'YTick', [1:4]*3/4+5/8, 'YTickLabels', {'A', 'B', 'C', 'D'});