MATLAB Answers

1

How do I add a legend to a boxplot in MATLAB?

Asked by MathWorks Support Team on 25 Apr 2014
Latest activity Edited by Noname
on 18 Dec 2016
I created a boxplot and would like to add a legend to it, but when I call legend I get the following warning message and there is no legend in the plot figure: 
 
Warning: Plot empty.
> In legend at 286
 
Is it possible to add a legend to a box plot? My code is: 
 
 
figure;
colors = [1 0 0; 1 0 0; 0 0 1; 0 0.5 0; 0 0.5 0; 0 0.5 0];
x = boxplot(rand(100,6),'Colors',colors);
legend('Group A','Group B','Group C')

1 Answer

Answer by MathWorks Support Team on 25 Apr 2014
 Accepted Answer

Box plots in the Statistics Toolbox do not support legends as of release R2014a.
As a workaround you can explicitly pass to the "legend" function the handle to the axes in which the box plot is drawn:
figure;
colors = [1 0 0; 1 0 0; 0 0 1; 0 0.5 0; 0 0.5 0; 0 0.5 0];
x = boxplot(rand(100,6), 'Colors',colors);
% findall is used to find all the graphics objects with tag "box", i.e. the box plot
hLegend = legend(findall(gca,'Tag','Box'), {'Group A','Group B','Group C'});
Depending on the number of variables that you have, you might not obtain the right color for each legend element. Use the following trick to manually change the color of each legend element:
% Among the children of the legend, find the line elements
hChildren = findall(get(hLegend,'Children'), 'Type','Line');
% Set the horizontal lines to the right colors
set(hChildren(6),'Color',[1 0 0])
set(hChildren(4),'Color',[0 0 1])
set(hChildren(2),'Color',[0 0.5 0])

  2 Comments

Hey,
thanks a lot for your solution, which helped me a lot! In R2014b, I can't get the children objects of the legend... Thus I solved to change the legend entry colors by the following dirty trick:
% findall is used to find all the graphics objects with tag "box", i.e. the box plot
box_vars = findall(gca,'Tag','Box');
hLegend = legend(box_vars([3,2,4]), {'Group 1','Group 2','Group 3'});
Perhaps it is useful for others. ;-) Thanks!
Thanks a million! I am student, your question and answers give me great help.Thanks a million!
% and I find findobj() can replace findall().
box_vars = findobj(gca,'Tag','Box');

Sign in to comment.