How to set legend for filled areas.

105 次查看(过去 30 天)
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')
%%-------------------------------

采纳的回答

Dimitris Iliou
Dimitris Iliou 2017-9-6
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:

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Legend 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by