get plot handles from existing legend from 2014b on

4 visualizaciones (últimos 30 días)
Julian Hapke
Julian Hapke el 9 de Feb. de 2016
Editada: Julian Hapke el 10 de Feb. de 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.
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

Respuestas (1)

Joseph Cheng
Joseph Cheng el 9 de Feb. de 2016
Editada: Joseph Cheng el 9 de Feb. de 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 comentarios
Joseph Cheng
Joseph Cheng el 9 de Feb. de 2016
Editada: Joseph Cheng el 9 de Feb. de 2016
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.
Julian Hapke
Julian Hapke el 10 de Feb. de 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.

Iniciar sesión para comentar.

Community Treasure Hunt

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

Start Hunting!

Translated by