简体   繁体   中英

Extract MATLAB legend string from existing plot

I've been trying to get some of the data back out of a plot that's been previously created, but I've been struggling with the legend. I'm using MATLAB 2014b.

If I previously set my plot up using:

h.fig   = figure();
h.ax    = axes(); hold all;
h.line1 = plot(0:0.01:2*pi(), sin(0:0.01:2*pi()));
h.line2 = plot(0:0.01:2*pi(), cos(0:0.01:2*pi()));
h.xlab  = xlabel('X');
h.ylab  = ylabel('Y');
h.leg   = legend('sin(x)', 'cos(x)');

Then without having h available I can still retrieve the x and y axis labels as strings:

xlab = get(get(gca, 'xlabel'), 'string');
ylab = get(get(gca, 'ylabel'), 'string');

However, I don't seem to be able to extract the text from a legend in a similar way. I notice that:

fig_children = get(gcf, 'children');

Shows me both the axes and legend as the children of the figure, but I don't seem to be able to access them in the same way I might with the axes:

ax = get(gca);

I'm probably mis-understanding something obvious about the way that it works, but I can't find a way to get the string out of a legend that's been previously made?

The legend text is associated to the line, rather than to a legend object, so:

ax_children = get(gca, 'children');

Outputs a line array of the lines I was plotting:

ax_children = 

  2x1 Line array:

  Line    (cos(x))
  Line    (sin(x))

And then:

leg_strings = get(ax_children, 'displayname');

Outputs a cell array:

leg_strings = 

    'cos(x)'
    'sin(x)'

Which is what I was looking for.

To get the legend handle (assuming only one exists in the figure, otherwise you'll have to sort them out) you can use the following:

findobj(gcf,'type','Legend')

ans = 

  Legend (sin(x), cos(x)) with properties:

         String: {'sin(x)'  'cos(x)'}
       Location: 'northeast'
    Orientation: 'vertical'
       FontSize: 9
       Position: [0.7226 0.8325 0.1589 0.0619]
          Units: 'normalized'

Then the legend entries are available as cell array.

In short:

leg_strings = get(findobj(gcf,'type','Legend'),'String');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM