How to get handle to legend in a specific axes?

조회 수: 66 (최근 30일)
KAE
KAE 2020년 2월 14일
답변: FWDekker 2024년 11월 15일 14:38
I would like to find the handle to one legend that appears in a specific subplot, while there are a lot of other plots with legends open. I know how to get a handle to all the legends, but not how to find the handle to one specific legend. Here is an example,
%% Make example plot with several subplots and legends
f1 = figure;
nSubplot = 3;
for iPlot = 1:nSubplot
ax(iPlot) = subplot(nPlot,1,iPlot); % Make an axis that will have its own legend
h1 = plot(rand(10,1), rand(10,1), '*'); % Plot some data
hold on;
h2 = plot(rand(10,1), rand(10,1), 'o');
box off;
hIgnore(iPlot) = legend([h1 h2], 'a', 'b'); % Make a legend in this subplot
% I know in this example I could create the legend handle hIgnore when I make the legend,
% but please ignore this approach since in the real code I must find the existing handle
end
%% Now try to get handle to legend from first subplot
hLeg = findobj('tag','legend'); % Returns handles to *all* legends, which we don't want
% Try to get handle to legend in first subplot only
hLeg = findobj(ax(1), 'tag','legend'); % Returns nothing, even though ax(1) is handle to first subplot

채택된 답변

Adam
Adam 2020년 2월 17일
Legends are parented by the figure, not the axes, so you get a list of figure children like this:
>> get( gcf, 'Children' )
ans =
6×1 graphics array:
Legend (a, b)
Axes
Legend (a, b)
Axes
Legend (a, b)
Axes
so I guess if you have the axes handle you may be able to search the figure's child list for the index of that axes, then take the legend handle previous to it (The child objects seem to be stored in reverse order and legends are apparently stored after their respective axes even if not added in that order - I tested creating all the axes and plots first, then all the legends and it still gave the above order)
As ever with having to fish out handles to graphics objects after the fact it is hacky and potentially brittle though.
So, like the joke about an Irishman in a small town being asked how to get to Dublin, answering 'Well, if I were you I wouldn't start from here!', if at all possible I would always keep hold of all my handles when I create the plots if I'm going to need them later on.
I would also give an explicit axes handle to the legend and plotting calls.

추가 답변 (1개)

FWDekker
FWDekker 2024년 11월 15일 14:38
The function legend allows you to pass an axes object, for which it will return the legend. So in your case, to get the legend of the first sub-figure, simply do legend(ax(1)). To see that this works, run title(legend(ax(1)), "My Title"), and only the title of the first legend will change.
(If someone tries to run OP's code and gets an error, note that nPlot should actually be nSubplot.)

카테고리

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