How to set legend for filled areas.

110 views (last 30 days)
Hello everyone,
the following code creates a figure with two shaded areas. My question is, how to label the areas by a legend or a colorbar. In this code the legend has wrong colors and the colorbar is neither in dark and light gray nor labeled.
Thanks for any help,
Stephan
%
%%-------------------------------
%%some unimportant definitions
N = 100;
xAXIS = linspace(0,1,N);
Y1 = repmat([-2;2],1,N);
Y2 = repmat([-1;1],1,N);
%%-------------------------------
figure; hold on;
%%area 1
h1=fill([xAXIS flip(xAXIS)], [Y1(1,:) flip(Y1(2,:))],'k','Edgecolor', 'none');
set(h1,'FaceAlpha',0.2)
%%area 2
h2=fill([xAXIS flip(xAXIS)], [Y2(1,:) flip(Y2(2,:))],'k','Edgecolor', 'none');
set(h2,'FaceAlpha',0.4);
%%y-axis
ylim([-2.5,2.5]);
%%-------------------------------
%%here is the problem
colorbar
legend('area 1','area 2')
%%-------------------------------

Accepted Answer

Dimitris Iliou
Dimitris Iliou on 6 Sep 2017
If I understand correctly, you want the FaceAlpha value of each patch in the legend to change according to the fill in the plot.
In order to do that, you need to change the FaceAlpha property of each patch contained in the legend by using legend as follows:
[~,h_legend] = legend('area1','area2');
After you do that, you need to find the patch objects.
PatchInLegend = findobj(h_legend, 'type', 'patch');
This will give you a 2x1 array of patches. The only thing you need to do after that, is set the FaceAlpha for each patch. You can do that by:
set(PatchInLegend(1), 'FaceAlpha', 0.2);
set(PatchInLegend(2), 'FaceAlpha', 0.4);
This code will produce the following figure:
  1 Comment
Stephan
Stephan on 6 Sep 2017
This is exactly what I need. Thank you very much!

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!