Why legend is not displayed?
32 views (last 30 days)
Show older comments
How can I display the legend at my desired side outside the figure? I run the following code but it doesn't work:
clear all; close all; clc
one=rand(100,1);
fitness2sn0=one';
one=rand(100,1);
fitness2sn5=one';
one=rand(100,1);
fitness2sn10=one';
one=rand(100,1);
fitness2sn15=one';
fitness2sn0=sort(fitness2sn0,'descend');
fitness2sn5=sort(fitness2sn5,'descend');
fitness2sn10=sort(fitness2sn10,'descend');
fitness2sn15=sort(fitness2sn15,'descend');
h1=boxplot([fitness2sn0; fitness2sn5; fitness2sn10; fitness2sn15].');
set(h1,{'linew'},{2})
grid
Ax = gca;
Ax.YLabel.String = '\bf fitness';
Ax.YScale = 'log';
Ax.XTickLabel = compose('2sn%d',[35 45 55 65]);
Ax.YLim = [1E-3 1e0];
title('\bf Fitness')
set(gca,'linew',2)
lgd = legend('35dB', '45dB','55dB','65dB')
lgd.Location = 'southoutside';
0 Comments
Accepted Answer
Simon Chan
on 5 Feb 2023
You may refer to this answer https://www.mathworks.com/matlabcentral/answers/127195-how-do-i-add-a-legend-to-a-boxplot-in-matlab
and do the modification like the following:
one=rand(100,1);
fitness2sn0=one';
one=rand(100,1);
fitness2sn5=one';
one=rand(100,1);
fitness2sn10=one';
one=rand(100,1);
fitness2sn15=one';
fitness2sn0=sort(fitness2sn0,'descend');
fitness2sn5=sort(fitness2sn5,'descend');
fitness2sn10=sort(fitness2sn10,'descend');
fitness2sn15=sort(fitness2sn15,'descend');
colors = [1 0 0; 0 0.5 0; 0.5 0 0; 0 0 0.5]; % Add different color
h1=boxplot([fitness2sn0; fitness2sn5; fitness2sn10; fitness2sn15]','Colors',colors);
set(h1,{'linew'},{2})
grid
Ax = gca;
Ax.YLabel.String = '\bf fitness';
Ax.YScale = 'log';
Ax.XTickLabel = compose('2sn%d',[35 45 55 65]);
Ax.YLim = [1E-3 1e0];
title('\bf Fitness')
set(gca,'linew',2)
hChildren = findall(gca,'Tag','Box');
lgd = legend(hChildren([4 3 2 1]), {'35dB','45dB','55dB','65dB'});
lgd.Location = 'southoutside';
11 Comments
DGM
on 5 Feb 2023
Simon's answer is the core of any solution to this problem, so it's appropriate that he gets credit. While it's sometimes unfortunate that comments can't be upvoted for emphasis, your comment is verification that it helped. That much is sufficient for my needs, and it should help any future readers with the same problem.
More Answers (0)
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!