如何在MATLAB的legend中添加多个标记点(非手动绘制)
MATLAB图例添加多标记点的非手动实现方法
以下是几种无需手动绘制标记点的可行方案:
方案1:创建带多标记的虚拟图例条目
通过生成仅包含重复标记的虚拟绘图对象,将其作为图例的输入条目,实现每个图例项显示多个同色标记:
% 原始绘图示例 figure; x = 1:10; h_line1 = plot(x, x, 'r-', 'LineWidth', 2); hold on; h_line2 = plot(x, 2*x, 'b-', 'LineWidth', 2); % 构建自定义图例用的虚拟对象 legend_handles = []; legend_labels = {'数据集1', '数据集2'}; line_colors = {'r', 'b'}; for idx = 1:length(line_colors) % 绘制仅含标记的虚拟对象(NaN坐标不会显示在主图中) h_virtual = plot(NaN, NaN, [line_colors{idx} 'o'], 'MarkerSize', 8); % 指定标记重复显示的次数,实现多个标记点效果 h_virtual.MarkerIndices = [1 2 3]; legend_handles = [legend_handles, h_virtual]; end % 替换原始图例 legend(legend_handles, legend_labels, 'Location', 'best'); hold off;
方案2:修改现有图例的条目属性
直接对已生成的图例对象进行属性修改,让每个图例条目的图标显示多个标记:
% 原始绘图示例 figure; x = 1:10; plot(x, x, 'r-', 'LineWidth', 2); hold on; plot(x, 2*x, 'b-', 'LineWidth', 2); % 创建默认图例并获取对象 lgd = legend('数据集1', '数据集2'); % 遍历每个图例条目,调整标记显示 for entry = lgd.EntryContainer.Children % 设置图标为"标记+线条"样式 entry.IconDisplayStyle = 'markerline'; % 指定显示多个标记点 entry.MarkerIndices = 1:3; entry.MarkerSize = 8; end
这两种方法都能自动生成带多个标记点的图例,无需手动在图例上绘制元素。
内容的提问来源于stack exchange,提问作者Luis Mendo
相关产品推荐
相关产品推荐

