如果您有 *.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数据提取到xData和yData。颜色信息保存到单元格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')
结果是右下图,每种颜色只列出一次。