MATLAB双图例字号不一致与标记过大问题解决方案咨询
MATLAB双图例字号统一与标记大小调整方案
问题原因解析
- 字号不一致:第二个图例绑定的隐藏轴
new_ax未同步原绘图轴的字体属性,且Position设置未明确单位,导致MATLAB自动缩放时字体显示比例异常。 - 标记大小无效:
ItemTokenSize属性仅对直接绑定到可见绘图轴的图例生效,绑定隐藏轴的图例需要直接修改标记对象的MarkerSize属性。
修改后的完整代码
Legend1 代码优化
legend1 = legend(legend_entries, ... 'FontName', 'Times New Roman', 'FontSize', 6,... 'Location', 'NorthEastoutside',... 'Box', 'on', 'NumColumns', 1, ... 'AutoUpdate', 'off'); % 提前关闭自动更新,避免属性被覆盖 % 明确归一化单位,确保位置尺寸不受窗口缩放影响 set(legend1, 'Units', 'normalized', 'Position', [0.84, 0.41, 0.1, 0.2]); legend1.ItemTokenSize = [10, 10];
Legend2 代码修复
if nargin > 1 && ~isempty(set_legend2) current_ax = gca; % 创建隐藏轴时同步原轴字体属性,保证渲染环境一致 new_ax = axes('Position', get(current_ax, 'Position'),... 'Units', get(current_ax, 'Units'), ... 'Visible', 'off', ... 'FontName', get(current_ax, 'FontName'), ... 'FontSize', get(current_ax, 'FontSize')); legend2 = legend(new_ax, set_legend2, plot_info.leg,... 'FontName', 'Times New Roman', 'FontSize', 6, ... 'Location', 'northwest', ... 'Box', 'off', 'NumColumns', 2, ... 'AutoUpdate', 'off'); % 明确归一化单位后设置位置 set(legend2, 'Units', 'normalized', 'Position', [0.55, 0.75, 0.1, 0.1]); % 直接修改图例标记大小,替代无效的ItemTokenSize legend_items = findobj(legend2, 'Type', 'Line'); for item = legend_items item.MarkerSize = 6; % 根据需求调整数值 end end
关键修改说明
- 同步字体环境:创建隐藏轴时复制原轴的字体属性,消除两个图例的渲染差异。
- 统一单位设置:所有图例位置设置前指定
Units为'normalized',避免窗口缩放导致的字体比例变化。 - 替换标记调整方式:通过遍历图例子对象修改
MarkerSize,解决隐藏轴图例ItemTokenSize无效的问题。 - 提前关闭自动更新:创建图例时直接关闭自动更新,防止MATLAB自动覆盖手动配置。
内容的提问来源于stack exchange,提问作者Lucy Yang
相关产品推荐
相关产品推荐

