从matplotlib图中获取最高zorder对象

时间:2018-02-01 15:04:29

标签: python matplotlib

给定matplotlib图或图,我如何检索最高zorder对象的值?例如,在此示例中检索5的值:

import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(1)
ax.plot(np.arange(10), np.arange(10), zorder=5, linewidth=5)
ax.plot(np.arange(10), np.arange(10)[::-1], zorder=1, linewidth=5)
# implement: get_maximum_zorder(ax) 

enter image description here

2 个答案:

答案 0 :(得分:1)

另一个答案获得了图中每个对象的z顺序。

print (ax.get_children())

# [matplotlib.lines.Line2D object at 0x104E63F0,
# matplotlib.lines.Line2D object at 0x104E6670,
# matplotlib.spines.Spine object at 0x0E6976D0,
# matplotlib.spines.Spine object at 0x0E697770,
# matplotlib.spines.Spine object at 0x0E697810,
# matplotlib.spines.Spine object at 0x0E6978B0,
# matplotlib.axis.XAxis object at 0x0E697950>,
# matplotlib.axis.YAxis object at 0x104CB170>,
# Text(0.5,1,''), Text(0,1,''), Text(1,1,''),
# matplotlib.patches.Rectangle object at 0x104DC4F0]

如果您想缩小搜索范围以仅包含图中的行,您可以使用ax.lines获取行列表,然后循环调用get_zorder()函数:

fig, ax = plt.subplots(1)
ax.plot(np.arange(10), np.arange(10), zorder=5, linewidth=5)
ax.plot(np.arange(10), np.arange(10)[::-1], zorder=1, linewidth=5)

lines = ax.lines
print (max(line.get_zorder() for line in lines))
# 5

# You can use .zorder here too!
# print (max(line.zorder for line in lines))

正如@tom在评论中指出的那样,您可以将ax.lines替换为ax.collectionsax.patchesax.artists,具体取决于所使用的地图类型

答案 1 :(得分:0)

这可以通过访问轴的孩子来完成,每个孩子都有zorder属性。

max([_.zorder for _ in ax.get_children()])