我知道如何使用图例功能的'Location'输入,但是没有一个选项可以将图例放在角落,它们都在图例和绘图边界之间留有很小的空间。我已经看到可以用向量指定位置,但是我不知道该怎么做。任何帮助表示赞赏。
这是一种方法。我以NorthEast
图例位置为例。对于其他职位,您可以使用类似的逻辑(请参见下文)。
plot([2 -2]) % example plot...
le = legend('abc', 'Location', 'northeast'); % ... with legend
pos_le = get(le, 'position');
pos_ax = get(gca, 'position');
set(le, 'position', [pos_le(1) pos_le(2) pos_ax(1)+pos_ax(3)-pos_le(1) pos_ax(2)+pos_ax(4)-pos_le(2)]); % new position
要了解其工作原理,请注意位置属性定义为
[lower_pos, left_pos, width, height]
因此,在这种情况下,图例宽度设置为轴左位置加上轴宽度减去图例左位置;和类似的图例高度。此逻辑适用于NorthEast
位置中的图例。对于其他位置,修改应该是显而易见的。
上面的缺点是,如果调整大小,则图例将不再对齐。要使其随着图形尺寸的变化而对齐,可以使用图形的SizeChangedFcn
属性来指定在调整图形大小时自动执行的代码(ResizeFcn
也可以,但是它是not recommended)。
plot([2 -2]) % example plot...
le = legend('abc', 'Location', 'northeast'); % ... with legend
set(gcf, 'SizeChangedFcn', 'le = findobj(gcf, ''type'', ''legend''); pos_le = get(le, ''position''); pos_ax = get(gca, ''position''); set(le, ''position'', [pos_le(1) pos_le(2) pos_ax(1)+pos_ax(3)-pos_le(1) pos_ax(2)+pos_ax(4)-pos_le(2)]);')
set(gcf, 'position', get(gcf, 'position')-1e-3) % force initial call to SizeChangedFcn
set(gcf, 'position', get(gcf, 'position')+1e-3) % restore initial position
示例: