Common legend for multiple histograms in subplots
조회 수: 18 (최근 30일)
이전 댓글 표시
Hi,
I'm trying to display multiple histograms on several subplots (to avoid them overlapping too much), but I'd like to have only one legend for all of them.
I am aware of that post: https://www.mathworks.com/matlabcentral/answers/98474-is-there-a-command-in-matlab-for-creating-one-overall-legend-when-i-have-a-figure-with-subplots Unfortunately, that solution doesn't work when you plot histograms instead of plots. Here is the exact same code as proposed as a solution in the previously mentioned post, but with histograms instead of plots:
% Construct a figure with subplots and data
subplot(2,2,1);
line1 = histogram(rand(1,1000));
title('Axes 1');
subplot(2,2,2);
line2 = histogram(rand(1,1000));
title('Axes 2');
subplot(2,2,3);
line3 = histogram(rand(1,1000));
title('Axes 3');
subplot(2,2,4);
line4 = histogram(rand(1,1000));
title('Axes 4');
% Construct a Legend with the data from the sub-plots
hL = legend([line1,line2,line3,line4],{'Data Axes 1','Data Axes 2','Data Axes 3','Data Axes 4'});
% Programatically move the Legend
newPosition = [0.4 0.4 0.2 0.2];
newUnits = 'normalized';
set(hL,'Position', newPosition,'Units', newUnits);
The legend is set, but we cannot see the colors of the histograms in the legend except for the first one.
I looked for a while for a solution, but haven't found one yet.
Does anybody know how to do that?
Thank you
댓글 수: 0
답변 (1개)
Thorsten
2018년 8월 9일
Set the FaceColor explicitly before calling legend:
set(line1, 'FaceColor', 'r')
set(line2, 'FaceColor', 'g')
set(line3, 'FaceColor', 'b')
set(line4, 'FaceColor', 'm')
hL = legend([line1,line2,line3,line4],{'Data Axes 1','Data Axes 2','Data Axes 3','Data Axes 4'});
댓글 수: 2
참고 항목
카테고리
Help Center 및 File Exchange에서 Legend에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!