当前有效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
本文介绍了matplotlib库中的findobj()函数,用于查找图形对象的子对象。函数接受容器对象、匹配规则作为参数,返回匹配的Artist列表。示例中展示了查找子图所有对象、特定类型对象以及通过回调函数筛选对象的方法。源码解析了函数内部实现。
506

被折叠的 条评论
为什么被折叠?



