2

A colleague has passed me a .fig file that has many lines on the same plots and they are coloured based on which group they belong to. The figure is shown below for reference.

I need to change the legend so that lines with the same colour have the same legend entry. The problem is that I don't have access to the raw data so I can't use the method mentioned here so is there a way to change the legend entries just using the .fig file? I tried changing some of the legend names to NaN in the property inspector but that just changes the entries to NaN.

What I have so far

gehbiszumeis
  • 3,525
  • 4
  • 24
  • 41
enea19
  • 113
  • 1
  • 11

1 Answers1

0

If you have the *.fig file you can extract any included data with the 'get' method if you have understood the MATLAB Graphics Objects Hierarchy.

For example, see the left plot below as example of your *.fig file. you can extract the data in there by digging through the Children of your current figure object.

% 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 data of all lines in the figure is now extracted to xData and yData. The color information is saved to cell cData. You can now replot the figure with a legend the way you want (e.g. using the SO solution you found already):

% 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')

Result is the plot below on the right, where each color is only listed once.

enter image description here

gehbiszumeis
  • 3,525
  • 4
  • 24
  • 41