【问题标题】:How to align logarithmic scale ticks across subplots?如何在子图中对齐对数刻度刻度?
【发布时间】:2019-07-02 08:13:58
【问题描述】:

我想固定刻度在对数刻度上的位置,以便它们在每个子图中都相同(参见图像中的红色注释)。 我的代码如下所示:

ax = fig.add_subplot(2,2, axis)
ax2 = ax.twinx()
ax2.set_yscale('log')
ax2.set_ylim(0,100)

现在,set_yscale=('log') 优化了每个子图的刻度间距。我更喜欢采用右上子图的刻度间距。

【问题讨论】:

    标签: python matplotlib subplot


    【解决方案1】:

    您可以通过获取左双轴的限制并将其设置为右双轴的限制来实现。

    考虑以下工作示例。对要对齐轴的子图执行此过程。



    import numpy as np
    import matplotlib.pyplot as plt
    
    fig = plt.figure(figsize=(8, 3))
    
    axl = fig.add_subplot(121)
    axr = fig.add_subplot(122)
    
    ax1 = axl.twinx()
    ax1.plot(np.logspace(-2, 3, 5))
    ax1.set_yscale('log')
    
    ax2 = axr.twinx()
    ax2.plot(np.logspace(0, 3, 5))
    ax2.set_yscale('log')
    
    ax2.set_ylim(ax1.get_ylim()) # <-- This is the key line
    
    plt.tight_layout()
    plt.show()
    

    【讨论】:

      【解决方案2】:

      OP的解决方案:

      绘制虚拟曲线并设置alpha=0。确保曲线跨越 y_min 和 y_max。

      fig = plt.figure()
      axes = [1,2,3,4]
      
      for axis in axes:
          ax = fig.add_subplot(2,2, axis)
          ax2 = ax.twinx()
          ax2.set_yscale('log')
          ax2.plot(x_dummy, y_dummy, alpha=0)            # <-- dummy plot
      
          x_real, y_real = func_that_loads_data()        # <-- your interesting plot 
          curve1 = ax2.plot(x_real, y_real)        
      
      plt.show()
      

      Sheldore 提供的解决方案实施起来不切实际,因为我使用 for 循环绘制数据(这是不可避免的,除非我增加变量的数量)。

      由于我在每次迭代中都覆盖了 ax 变量,因此我必须将 y 限制保存为全局变量。 Read here why global variables should be avoided.

      ax = fig.add_subplot(2,2, axis)
      ax2 = ax.twinx()
      ax2.set_yscale('log') 
      
      if axis == 1:
          global yscale
          yscale = ax2.get_ylim()                       # <-- where the magic happens
      elif axis > 1:
          ax2.set_ylim(yscale)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-11-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-07
        • 2022-01-02
        • 1970-01-01
        • 2012-12-03
        • 2013-01-09
        相关资源
        最近更新 更多