代码之家  ›  专栏  ›  技术社区  ›  KansaiRobot

如何在matplotlib中适当设置轴的限制

  •  0
  • KansaiRobot  · 技术社区  · 2 年前

    我有一个数据帧

    import pandas as pd
    import matplotlib.pyplot as plt
    import numpy as np
    
    data = {
        'id': [1, 2, 3, 4, 5,6,7,8,9,10],
        'LeftError': [0.1, 0.2, 0.15, 0.3, 0.25,-0.1, -0.2, -0.15, -0.3, -0.25],
        'RightError': [0.2, 0.3, 0.25, 0.4, 0.35,-0.2, -0.3, -0.25, -0.4, -0.35],
        'NCL': [1, 2, 1, 3, 2,-1, -2, -1, -3, -2],
        'NCR': [2, 3, 2, 4, 3,-2, -3, -2, -4, -3],
    }
    
    df = pd.DataFrame(data)
    

    我想把它画出来

        fig, axes = plt.subplots(1, 2, figsize=(12, 5))
    
        # Plot for Left side
        axes[0].scatter(df['NCL'], df['LeftError'], color='blue')
    
        axes[0].set_xlabel('NCL')
        axes[0].set_ylabel('Left Error')
    
        # Plot for Right side
        axes[1].scatter(df['NCR'], df['RightError'], color='green')
    
        axes[1].set_xlabel('NCR')
        axes[1].set_ylabel('Right Error')
    
        plt.show()
    

    然而,当我这样做时,我会 enter image description here

    你可以看到这里有好事也有坏事。好的方面是,Y轴比值的范围大一点,也小一点(它不交叉点)。糟糕的是,他们表现出不同的价值观。所以为了纠正我做的坏事

    axes[0].set_ylim((min(df['LeftError'].min(), df['RightError'].min())), (max(df['LeftError'].max(), df['RightError'].max())))
    axes[1].set_ylim((min(df['LeftError'].min(), df['RightError'].min())), (max(df['LeftError'].max(), df['RightError'].max())))
    

    现在我明白了

    enter image description here

    所以坏事得到了纠正,但好事变成了坏事。看到第一个和最后一个绿点被轴交叉了

    如何使轴与原来一样有一些衬垫,但保持两者的值相同?

    1 回复  |  直到 2 年前
        1
  •  1
  •   jared    2 年前

    您可以使用已填充的 xlim s和 ylim s的情节。你只需要取所有轴极限的最小值和最大值。

    import numpy as np
    import matplotlib.pyplot as plt
    
    plt.close("all")
    
    x1 = np.linspace(-4, 4, 10)
    x2 = np.linspace(-3, 3, 10)
    y1 = 2*x1
    y2 = 3*x2
    
    fig, axes = plt.subplots(1, 2)
    axes[0].scatter(x1, y1)
    axes[1].scatter(x2, y2)
    
    xlim = (min([ax.get_xlim()[0] for ax in axes]),
            max([ax.get_xlim()[1] for ax in axes]))
    ylim = (min([ax.get_ylim()[0] for ax in axes]),
            max([ax.get_ylim()[1] for ax in axes]))
    
    plt.setp(axes, xlim=xlim, ylim=ylim)