问题
The following stackoverflow qestion:
Matlab: How to obtain all the axes handles in a figure handle?
identifies how to get handles to all of the axes from a figure in Matlab. However, this list will also contain handles to legends, at least in R2008a, which appear to also be axes. How can I tell (programatically) the legends from the real plot axes in a vector of axes handles?
回答1:
From linkaxes
, the code you want is:
ax = findobj(gcf,'type','axes','-not','Tag','legend','-not','Tag','Colorbar');
This will return the handles of all the data axes in the current figure.
回答2:
1) By default the Tag
property of legend is 'Legend'. Of course, there is no promise that it is not changed.
get(l)
....
BusyAction: 'queue'
HandleVisibility: 'on'
HitTest: 'on'
Interruptible: 'off'
Selected: 'off'
SelectionHighlight: 'on'
**Tag: 'legend'**
Type: 'axes'
UIContextMenu: 200.0018
UserData: [1x1 struct]
....
2) Another difference (which is more robust) is that regular axes do not have String
property, but legends do. I am not sure whether there are other types of objects that also have String
property. For example:
plot(magic(3));legend('a','v','b');
allAxesInFigure = findall(f,'type','axes')
b = isprop(allAxesInFigure,'String')
You can verify it by calling:
get(gca,'String')
??? Error using ==> get
There is no 'String' property in the 'axes' class.
But on the other hand, for legends there is such a property. That is why it is more robust.
plot(magic(3)); l = legend('a','b','c');
get(l,'String')
ans = 'a' 'b' 'c'
3) I would recommend to solve this in a broader context. Just keep track of the legends and axes you create by storing their handles. That is, instead of coding like:
plot(magic(3));
legend('a','v','b');
plot(magic(5));
legend('a','v','b','c','d');
Code like this:
p(1) = plot(magic(3));
l(1) = legend('a','v','b');
p(2) = plot(magic(5));
l(2) = legend('a','v','b','c','d');
回答3:
Just slightly modifying the code of my answer at the stackoverflow question you mentioned:
axesHandles = get(fig, 'Children');
classHandles = handle(axesHandles);
count = length(axesHandles);
isLegend = false(1, count);
for i = 1:count
isLegend(i) = strcmp(class(classHandles(i)), 'scribe.legend') == 1;
end
legendHandles = axesHandles(isLegend);
Unfortunately, this solution depends on implementation details.
来源:https://stackoverflow.com/questions/9071988/how-to-tell-legends-from-axes-in-matlab