Why legend is not displayed?
조회 수: 30 (최근 30일)
이전 댓글 표시
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
채택된 답변
Simon Chan
2023년 2월 5일
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
DGM
2023년 2월 5일
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.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Data Distribution Plots에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!