Plot legend position changes between fig in live script and external window
조회 수: 5 (최근 30일)
이전 댓글 표시
I'm tring to position the legend so it does not appear above my data. Therefore, I'm changing the position vector of the legend. But the image is different in the output of the mlx, and the external windows. This only occurs when also changing the figure props. But what causes this problem?
MWE:
figure
hold all
plot(1:10)
plot(10:-1:1);
hold off
leg = legend
leg.Position = [0.5 0.5 0.40 0.4];
x0=10;
y0=10;
width = 6
height = 6
set(gcf,'units','centimeters','position',[x0,y0,width,height])
EDIT: I'm using R 2019b.

댓글 수: 0
채택된 답변
Adam Danz
2021년 3월 16일
편집: Adam Danz
2021년 3월 18일
The figure position when embedded in a live script is not the same as the figure position when undocked. Therefore, you shouldn't be specifying the legend size (which is relative to the figure). Creat the legend and change the position only, which are the first two values of the Position property.
Example: Legend position is centered horizontally within the axes
leg = legend();
leg.Position(1) = .5 - leg.Position(3)/2;
Or, better yet, why not set the legend location rather than position?
leg = legend('Location','bestoutside')
% leg.Position = [0.5 0.5 0.40 0.4] remove this
댓글 수: 2
Adam Danz
2021년 3월 22일
It's not clear why the inset makes the 'bestoutside' option not useful. Is it because the axis size changes? That's fixable. Just record the axis size before setting the legend and then return the axis size after setting the legend.
> I don't see that the legend size, as you say, is relative to the figure
The default units for legends is normalized which means the position is relative to the figure space. In this line below you are setting the legend size to 40% the fig width and 40% the figure height.
leg.Position = [0.5 0.5 0.40 0.4];
% ^^^^ ^^^^
Instead, just set the legend position (first 2 position values) and leave the size alone (last 2 position values). That's what my answer does. It moves the legend to the horizontal center of the axes.
But I still think setting the legend to outside is best. Or try,
legend(__, 'Orientation','Horizontal','location','SouthOutside') % or outsideNorth
again, if axis position is important, record axis position before setting the legend and return its original size after setting the legend.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Legend에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!