How to tell legends from axes in Matlab?

前端 未结 3 804
有刺的猬
有刺的猬 2021-02-09 21:06

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 figur

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-09 22:03

    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');
    

提交回复
热议问题