Python 如何检测是否为matplotlib轴生成了双轴

Python 如何检测是否为matplotlib轴生成了双轴,python,matplotlib,Python,Matplotlib,如何检测轴的顶部是否写有双轴?例如,如果下面给定了ax,我如何发现ax2存在 import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.plot([1, 2, 3]) ax2 = ax.twinx() 我不认为有任何内置功能可以做到这一点,但您可能只需要检查图形中的任何其他轴是否与所讨论的轴具有相同的边界框。下面是一个可以实现此目的的快速片段: def has_twin(ax): for other_ax in ax.fig

如何检测轴的顶部是否写有双轴?例如,如果下面给定了
ax
,我如何发现
ax2
存在

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3])
ax2 = ax.twinx()

我不认为有任何内置功能可以做到这一点,但您可能只需要检查图形中的任何其他轴是否与所讨论的轴具有相同的边界框。下面是一个可以实现此目的的快速片段:

def has_twin(ax):
    for other_ax in ax.figure.axes:
        if other_ax is ax:
            continue
        if other_ax.bbox.bounds == ax.bbox.bounds:
            return True
    return False

# Usage:

fig, ax = plt.subplots()
print(has_twin(ax))  # False

ax2 = ax.twinx()
print(has_twin(ax))  # True

您可以检查轴是否具有共享轴。但这不一定是双胞胎。但再加上对职位的质疑,这就足够了

import matplotlib.pyplot as plt

fig, axes = plt.subplots(2,2)
ax5 = axes[0,1].twinx()

def has_twinx(ax):
    s = ax.get_shared_x_axes().get_siblings(ax)
    if len(s) > 1:
        for ax1 in [ax1 for ax1 in s if ax1 is not ax]:
            if ax1.bbox.bounds == ax.bbox.bounds:
                return True
    return False

print has_twinx(axes[0,1])
print has_twinx(axes[0,0])

我想提出一个
get\u twin->Axes
函数,而不是
has\u twin->bool
,它有更多的应用。如果get_twin(…)为None,您仍然可以通过检查
而不是
if has_twin(…)
来检查ax是否有twin,这样功能性就不会丢失

这是建立在@ImportanceOfBeingErnest的答案之上的@jakevdp的健壮性稍差,因为它不明确检查兄弟姐妹

def get_twin(ax, axis):
    assert axis in ("x", "y")        
    siblings = getattr(ax, f"get_shared_{axis}_axes")().get_siblings(ax)
    for sibling in siblings:
        if sibling.bbox.bounds == ax.bbox.bounds and sibling is not ax:
            return sibling 
    return None

fig, ax = plt.subplots()
print(get_twin(ax, "x") is None) # True
ax2 = ax.twinx()
print(get_twin(ax, "x") is ax2)  # True
print(get_twin(ax2, "x") is ax)  # True

那就够了!twins_of_ax=[a代表fig.axes中的a,如果a!=ax和a.bbox.bounds==ax.bbox.bounds]@michaelosthege
twins_of_ax=[a代表a.figure.axes中的a,如果a不是ax和a.bbox.bounds==ax.bbox.bounds]
,因此您只需要测试的ax作为变量,甚至它不是figure。