How to set legend for filled areas.
조회 수: 108 (최근 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')
%%-------------------------------
댓글 수: 0
채택된 답변
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 Center 및 File Exchange에서 Legend에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!