更改图形的图例,使多条线共享相同的图例条目

Changing the legend of a figure so that various lines share the same legend entry

一位同事传给我一个 .fig 文件,该文件在同一图上有很多行,并且根据它们所属的组对它们进行了着色。下图供参考

我需要更改图例,使颜色相同的线条具有相同的图例条目。问题是我无法访问原始数据,所以我不能使用提到的方法 here 那么有没有办法只使用 .fig 文件来更改图例条目?我尝试在 属性 检查器中将一些图例名称更改为 NaN,但这只会将条目更改为 NaN。

如果您有 *.fig 文件,并且您了解 MATLAB Graphics Objects Hierarchy.

,则可以使用 'get' 方法提取任何包含的数据

例如,请参阅下面的左图作为 *.fig 文件的示例。您可以通过挖掘当前图形对象的 Children 来提取其中的数据。

% Open your figure
fig = openfig('your_figure.fig');
% fig = gcf     % If you have the figure already opened
title('loaded figure')

% Get all objects from figure (i.e. legend and axis handle)
Objs = get(fig, 'Children');      
% axis handle is second entry of figure children
HA = Objs(2);          
% get line objects from axis (is fetched in reverse order)
HL = flipud(get(HA, 'Children'));     

% retrieve data from line objects
for i = 1:length(HL)
    xData(i,:) = get(HL(i), 'XData');
    yData(i,:) = get(HL(i), 'YData');
    cData{i} = get(HL(i), 'Color');
end

图中所有线的xy数据现在被提取到xDatayData。颜色信息保存到单元格 cData。您现在可以按照您想要的方式重新绘制带有图例的图形(例如,使用您已经找到的 SO 解决方案):

% Draw new figure with data extracted from old figure
figure()
title('figure with reworked legend')
hold on
for i = 1:length(HL)
    h(i) = plot(xData(i,:), yData(i,:), 'Color', cData{i});
end

% Use method of the SO answer you found already to combine equally colored
% line objects to the same color
legend([h(1), h(3)], 'y1', 'y2+3')

结果是右下图,其中每种颜色只列出一次。