matplotlib之pyplot模块——递归查找对象(findobj())

当前有效matplotlib版本为:3.4.1

概述

findobj()函数的作用是递归查找对象中包含的子对象。

函数的签名为matplotlib.pyplot.findobj(o=None, match=None, include_self=True)
函数的参数为:

  • o:容器对象,即需要查找子对象的对象。默认值为None,即当前图形对象。
  • match:匹配规则。默认值为None。取值要求如下:
    • None:当前artist包含的所有子对象。
    • 可调用对象: 匹配函数。签名要求为def match(artist: Artist) -> bool。 返回匹配函数返回值为True的对象列表。
    • 类实例:例如Line2D。返回包含该类或该类子类的对象。根据源码可知,底层使用isinstance函数检验。

返回值为Artist列表。

案例:演示findobj()函数

import matplotlib.pyplot as plt

ax =plt.gca()
line,=plt.plot([2,1],label="1")

# 列出当前子图中的所有对象
plt.findobj(ax)
# 列出当前子图中的所有Line2D对象
from matplotlib.lines import Line2D
plt.findobj(ax,Line2D)
# 编写回调函数过滤标签为1的Line2D对象
def find_match(x):
    return plt.getp(x,"label")=="1"
       
plt.findobj(match=find_match)
# 编写回调函数过滤标签为1的Line2D对象
plt.findobj(match=lambda x:x.get_label()=='1')

plt.show()

源码

matplotlib.pyplot

def findobj(o=None, match=None, include_self=True):
    if o is None:
        o = gcf()
    return o.findobj(match, include_self=include_self)

matplotlib.artist.Artist

def findobj(self, match=None, include_self=True):
    if match is None:  # always return True
        def matchfunc(x):
            return True
    elif isinstance(match, type) and issubclass(match, Artist):
        def matchfunc(x):
            return isinstance(x, match)
    elif callable(match):
        matchfunc = match
    else:
        raise ValueError('match must be None, a matplotlib.artist.Artist '
                            'subclass, or a callable')

    artists = sum([c.findobj(matchfunc) for c in self.get_children()], [])
    if include_self and matchfunc(self):
        artists.append(self)
    return artists
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值