【问题标题】:How to define zorder when using 2 y-axis?使用2个y轴时如何定义zorder?
【发布时间】:2021-06-02 22:11:28
【问题描述】:

我在 matplotlib 图形的左侧和右侧使用两个 y 轴进行绘图,并使用 zorder 来控制绘图的位置。我需要在同一图中定义zorder across 轴。


问题

import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-10,10,0.01)

fig, ax1 = plt.subplots( 1, 1, figsize=(9,3) )
ax1.plot( x, np.sin(x), color='red', linewidth=10, zorder=1 )
ax2 = ax1.twinx()
ax2.plot( x, x, color='blue', linewidth=10, zorder=-1)

在上图中,我希望蓝线出现在红色图的后面。

使用双轴时如何控制zorder


我正在使用:

python:3.4.3 + numpy:1.11.0 + matplotlib:1.5.1

【问题讨论】:

    标签: python numpy matplotlib


    【解决方案1】:

    这应该可以工作

    ax1.set_zorder(ax2.get_zorder()+1)
    ax1.patch.set_visible(False)
    

    【讨论】:

    • 是的,它奏效了。虽然我们需要更改一些代码。
    【解决方案2】:

    以下代码有效

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib import ticker as tick
    
    
    x = np.arange(-10,10,0.01)
    
    plt.figure(figsize=(10, 5))    
    fig = plt.subplot(111)
    
    """be attention to here. it's fig.plot, not ax1.plot
    if you write ax1.plot, then it does not work.
    """
    fig.plot(x, x, color ='blue', linewidth =10) 
    
    ax2 = fig.twinx()    
    ax2.plot(x, np.sin(x), color='red', linewidth =10) 
    
    """
    It looks like the two axes have separate z-stacks. 
    The axes are z-ordered with the most recent axis on top
    """
    fig.set_zorder(ax2.get_zorder()+1)
    fig.patch.set_visible(False)
    plt.show()
    

    【讨论】:

      【解决方案3】:

      看起来这两个轴有单独的 z 堆栈。轴按 z 顺序排列,最近的轴位于顶部,因此您需要将所需的曲线移动到您创建的最后一个轴:

      import numpy as np
      import matplotlib.pyplot as plt
      x = np.arange(-10,10,0.01)
      
      fig, ax1 = plt.subplots( 1, 1, figsize=(9,3) )
      ax1.plot( x, x, color='blue', linewidth=10 )
      ax2 = ax1.twinx()
      ax2.plot( x, np.sin(x), color='red', linewidth=10 )
      

      【讨论】:

      • 嗯...不。如果您更改绘图顺序,它保持不变。在您的代码中,您将ax1 更改为ax2(即左和右),而不是情节顺序:)
      • 谢谢,我就是这个意思;我将回复编辑得更具体
      猜你喜欢
      • 2016-10-26
      • 1970-01-01
      • 2019-11-25
      • 1970-01-01
      • 1970-01-01
      • 2017-07-14
      • 1970-01-01
      相关资源
      最近更新 更多