get plot handles from existing legend from 2014b on

2 views (last 30 days)
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)

Joseph Cheng
Joseph Cheng on 9 Feb 2016
Edited: Joseph Cheng on 9 Feb 2016
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
Julian Hapke
Julian Hapke on 10 Feb 2016
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.

Community Treasure Hunt

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

Start Hunting!