find line handles related to legend entries

23 次查看(过去 30 天)
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?

采纳的回答

Mike Garrity
Mike Garrity 2015-7-7
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.

更多回答(1 个)

Brendan Hamm
Brendan Hamm 2015-7-7
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 个评论
Peter
Peter 2015-7-7
thanks Brendan, the thing is that for your solution i should have somehow stored the handles of the lines, which i didn't.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Legend 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by