【问题标题】:How to detect if a twin axis has been generated for a matplotlib axis如何检测是否为 matplotlib 轴生成了双轴
【发布时间】:2016-03-24 20:36:39
【问题描述】:

如何检测轴上是否写有双轴?比如下面给出ax,如何发现ax2存在?

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

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    我认为没有任何内置功能可以执行此操作,但您可能只需检查图中的任何其他轴是否与相关轴具有相同的边界框。这是一个可以执行此操作的快速 sn-p:

    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
    

    【讨论】:

    • 应该这样做!
    • twins_of_ax = [a for a in fig.axes if a != ax and a.bbox.bounds == ax.bbox.bounds]
    • @michaelosthege twins_of_ax = [a for a in a.figure.axes if a is not ax and a.bbox.bounds == ax.bbox.bounds] 这样你只需要测试的斧头作为变量,甚至不需要它的数字。
    【解决方案2】:

    您可以检查轴是否有共享轴。不过,这不一定是双胞胎。但是加上查询位置就足够了。

    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])
    

    【讨论】:

      【解决方案3】:

      我想提出一个get_twin -> Axes函数而不是has_twin -> bool,它有更多的应用程序。您仍然可以通过检查 if get_twin(...) is None 而不是 if has_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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-27
        • 2017-10-11
        • 2023-03-04
        • 1970-01-01
        相关资源
        最近更新 更多