Plot legend position changes between fig in live script and external window
5 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Tracy Carla Rios Reyes
il 16 Mar 2021
Commentato: Adam Danz
il 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 Commenti
Risposta accettata
Adam Danz
il 16 Mar 2021
Modificato: Adam Danz
il 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 Commenti
Adam Danz
il 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.
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Legend in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!