Common legend for multiple histograms in subplots

85 views (last 30 days)
Laurent Chauvin
Laurent Chauvin on 9 Aug 2018
Commented: Laurent Chauvin on 10 Aug 2018
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

Answers (1)

Thorsten
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
Laurent Chauvin
Laurent Chauvin on 10 Aug 2018
Hum okay. I'm not sure to understand what is going on, but before I was calling 'legend' at the end of my script to create my histograms, and it wasn't working. However, now I removed it, and I use the 'legend' command when my script is done and has generated the histograms and it works.
Could this be a multithread issue (like legend is called before all my graphs are done, thus creating an issue) ?

Sign in to comment.

Products


Release

R2015b

Community Treasure Hunt

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

Start Hunting!