How to set legend for filled areas.

조회 수: 108 (최근 30일)
Stephan
Stephan 2017년 8월 30일
댓글: Stephan 2017년 9월 6일
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:
  댓글 수: 1
Stephan
Stephan 2017년 9월 6일
This is exactly what I need. Thank you very much!

댓글을 달려면 로그인하십시오.

추가 답변 (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