find line handles related to legend entries

23 views (last 30 days)
Before R15 I used to be able to find the handle of an object, referred to in the legend of an existing graph by a certain legend string, say "measured" as follows:
hlegend=findobj(gcf,'Type','axes','Tag','legend');
legenddata=get(hlegend,'userdata');
legendstrings=legenddata.lstrings;
ii=find(strcmp('measured', legendstrings));
h_measured=legenddata.handles(ii);
I dont see how to do something similar with the new graphics handles system in R15. Any suggestions?

Accepted Answer

Mike Garrity
Mike Garrity on 7 Jul 2015
For your purposes here, I would think that the easiest is to use the DisplayName property on the objects. That matches the string that the legend is showing.
Consider this example:
%%Create a plot with a legend
plot(magic(5))
legend('first','second','third','fourth','fifth')
%%Get a handle to the legend
%
% The type has changed because legends are no longer axes.
%
l = findobj(gcf,'Type','legend')
%%Loop over the legend entries and set the linewidth of the corresponding object
%
% Our legend has five strings. Each line object has a DisplayName which
% matches one of those strings.
%
for ix=1:length(l.String)
str = l.String{ix}
h = findobj(gcf,'DisplayName',str);
h.LineWidth = ix;
end
The result looks like this:
It looks like you might already know the DisplayName of the object you're looking for. If that's the case, you could skip getting the legend completely.

More Answers (1)

Brendan Hamm
Brendan Hamm on 7 Jul 2015
The legend will no longer store this information unless you pass it to the UserData. I would suggest returning the objects created by your various graphics commands anytime you will need to access the data later.
f = figure;
ax = axes;
p = plot(randn(100,5)); % Make a plot of some random data
leg = legend('A','B','C','D','E'); % Create legend and return the object
leg.UserData = p; % We could assign the handles to the legend directly
idx = strcmp(leg.String,'B')
B = leg.UserData(idx) % returns the Line object
% We don't really need to store to the UserData.
Balt = p(idx); % Alternative without storage.
  1 Comment
Peter
Peter on 7 Jul 2015
thanks Brendan, the thing is that for your solution i should have somehow stored the handles of the lines, which i didn't.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!