Common legend for multiple histograms in subplots
23 views (last 30 days)
Show older comments
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 Comments
Answers (1)
Thorsten
on 9 Aug 2018
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 Comments
See Also
Categories
Find more on Data Distribution Plots in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!