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.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

关于python - 如何检测是否为matplotlib轴生成了双轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36209575/

相关文章:

python - 如何在 Odoo 中预先获取表单中的默认字段值?

python - 打开文本框时出现第二个弹出框

python - 如何在 pytorch 中使用多个 GPU 训练模型?

python - 在Cygwin中使用Python的startapp时没有这样的文件或目录错误

matplotlib - 添加与第一个 y 轴相关的第二个 y 轴

python - 使用 scipy.signal.dstep 绘制离散传递函数

python matplotlib 标签/标题错误字符

python - 在类级容器初始化中调用静态方法

python - matplotlib 中的非闭合轮廓?

python - 用频率表绘制频率分布/直方图