how to keep lengends in the axis area after using pbaspect in matlab?

22 Views Asked by At

I want to use the pbaspect function to change the ratio between x-axis and y-axis. However, after using this function, the legends will be put outside of the axis area even if I using legend(..., "Location", "best").

Here is a short example of the matlab code(the picture below is the result of this code):

close all; clear; clc;

x = 0 : 0.01 : 2*pi;
y1 = sin(x);
y2 = cos(x);


figure;
plot(x, y1);
hold on;
plot(x, y2);
pbaspect([3 1 1]);
hold off;
legend("sin", "cos", "Location", "best");

I tried to change the order of plot, pbaspect, legend and hold on/off, but the result would not change. Because I have to plot thousands of figures for a dataset, it's alittle bit fussy to mannually adjust the location of legends of every picture.

So I wonder that is there a better way to make legend(..., "Location", "best") work when using pbaspect function? Thanks!

enter image description here

1

There are 1 best solutions below

0
X Zhang On

I feel you have already decided to keep the 'best' method instead of using a fixed position, then re-scale the figure could help a bit (see the last line).

close all; clear; clc;

x = 0 : 0.01 : 2*pi;
y1 = sin(x);
y2 = cos(x);


fh=figure;
plot(x, y1);
hold on;
plot(x, y2);
pbaspect([3 1 1]);
hold off;
legend("sin", "cos", "Location", "best");
% ~~~~~~~~
fh.Position(3)=fh.Position(3).*2;
% ~~~~~~~~

enter image description here