❤️1. 使用 Location 参数设置图例位置
h_legend = legend({'系列 A', '系列 B', '系列 C'}, ...
'FontName', 'Arial', ... % 指定字体名称
'FontSize', 10, ... % 指定字体大小
'Location', 'northeast'); % 指定初始位置在右上角
调用 legend 函数,并通过 Location 参数指定图例放置的位置。常用的 Location 参数有:
💗坐标轴内部位置: (将图例放置在坐标轴区域内)
- ‘north’:图例位于图上部中间
- ‘south’:图例位于图下部中间
- ‘east’:图例位于图右侧中间
- ‘west’:图例位于图左侧中间
- ‘northeast’:图例位于图右上角(默认常用)
- ‘northwest’:图例位于图左上角
- ‘southeast’:图例位于图右下角
- ‘southwest’:图例位于图左下角
💗坐标轴外部位置: (将图例放置在坐标轴区域之外)
- ‘northeastoutside’: 坐标轴区域右上角外部
- ‘northwestoutside’: 坐标轴区域左上角外部
- ‘southeastoutside’: 坐标轴区域右下角外部
- ‘southwestoutside’: 坐标轴区域左下角外部
- ‘northoutside’: 坐标轴区域上部外部居中
- ‘southoutside’: 坐标轴区域下部外部居中
- ‘eastoutside’: 坐标轴区域右侧外部居中
- ‘westoutside’: 坐标轴区域左侧外部居中
💗自动选择位置
自动选择位置:
- ‘best’:MATLAB 自动选择一个不遮挡图形的最佳位置
- ‘bestoutside’: MATLAB 尝试在坐标轴外部寻找最佳位置。
💗不指定位置
- ‘none’:不会自动放置图例,但会创建图例对象,其句柄 (h_legend)
❤️2. 手动调整图例位置
- 获取图例句柄
% 获取图例句柄
h_legend = legend({'a', 'b', 'c'}, ...
'FontName', '宋体', ...
'FontSize', 6, ...
'Location', 'northeast');
- 获取当前图例位置
‘Position’ 属性记录了它的位置和大小。我们用 get 函数来获取它
% 获取当前图例位置
pos = get(h_legend, 'Position'); % pos = [left bottom width height]
- 调整位置
注意: 这里的 0.05 是相对于坐标轴尺寸的比例。
pos(1)=pos(1)+0.05; %向右边移动5% 这个是横坐标的5%
pos(2)=pos(2)+0.05;%向上移动5%的距离 ,这个纵坐标范围的5%
- 设置新的位置
set(h_legend,'Position',pos)