Plot legend position changes between fig in live script and external window
11 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Tracy Carla Rios Reyes
le 16 Mar 2021
Commenté : Adam Danz
le 22 Mar 2021
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 commentaires
Réponse acceptée
Adam Danz
le 16 Mar 2021
Modifié(e) : Adam Danz
le 18 Mar 2021
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 commentaires
Adam Danz
le 22 Mar 2021
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.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Legend dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!