get plot handles from existing legend from 2014b on

On pre 2014b graphic handling the following code to retrieve the displayed strings and the handles of the referenced plot elements worked. From 2014b on it does not, because the legend() command may not be used with a legend handle.
figure;
plot(rand(10));
h = legend('bla');
[~,~,legplts,legstr] = legend(h);
Can you tell me how I can get the desired Information from an existing legend in 2014b?
Thanks!
edit after Joseph Cheng's answer:
my question was a bit vague. I need a robust solution for when there is more than one legend and/or axis in the figure and not all lines have a legend entry, so here is a more detailed example:
figure
subplot(1,2,1)
plot(rand(10,1),rand(10,1),rand(10,1),rand(10,1))
h=legend('bla')
subplot(1,2,2)
plot(rand(10,1),rand(10,1),rand(10,1),rand(10,1))
[~,~,legplts,legstr] = legend(h); % gives an error
I need to use the last command or at least get the information it used to provide from an existing figure. getting the legend handle is no problem, but determining the referenced plots is difficult for me

Answers (1)

you can extract that data in a way like this:
figure;
originaldata = rand(10);
plot(originaldata);
h = legend('bla','blu');
% [~,~,legplts,legstr] = legend(h); %pre 2014b (works in 2014a)
legstr = get(h,'string') %get legend strings
hfig = get(h,'parent') %get figure handle
cfig=get(hfig,'children') %get figure's children
hplot = get(cfig(1).Axes,'children'); %get plots in the first axes entry (the plots)
%second entry is the legend graphics if i'm not mistaken
%lets pull out the plotted data and check to see if that matches the original data
for ind = 1:10
extracted(:,ind) = get(hplot(ind),'YData');
end
%should be ≈0
sum(originaldata(:)-extracted(:))
step through and look at each handle call and you can see what data you can pull out where.

3 Comments

this way I only get all the plots in an axes, but not every plot has to have a legend entry, so in your code length(hplot) is not necessarily length(legplts)
btw: guessing that index 1 is your axes is not a good way, more reliable way:
findobj(cfig,'flat','type','axes','tag','')
also your way won't work properly if there are more than one legend and/or axes in your figure.
my answer was very user case dependent, but was an entry of what you'd probably going to have to do. Based of your vague question, it was just looking for ways of getting the data that was used to be stored in the legend() output. Normally i would have saved what i plotted if i needed their handles.
you're right, for the example it does what I want and I'm thankful for your help. I will edit my question, so I get the robust solution I'm really looking for.

Sign in to comment.

Asked:

on 9 Feb 2016

Edited:

on 10 Feb 2016

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!