get plot handles from existing legend from 2014b on

7 views (last 30 days)
Julian Hapke
Julian Hapke on 9 Feb 2016
Edited: Julian Hapke on 10 Feb 2016
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.
h = legend('bla');
[~,~,legplts,legstr] = legend(h);
Can you tell me how I can get the desired Information from an existing legend in 2014b?
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:
[~,~,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:
originaldata = rand(10);
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');
%should be ≈0
step through and look at each handle call and you can see what data you can pull out where.
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!