【问题标题】:How to require equal axes in matplotlib如何在 matplotlib 中要求等轴
【发布时间】:2022-01-11 23:51:14
【问题描述】:

我习惯于使用下面的代码生成完全比例轴的 python 版本。

    plt.ylabel("y(Km)")
    plt.gca().set_aspect('equal')
    ax = plt.axes()
    ax.set_facecolor("black")
    circle = Circle((0, 0), 2, color='dimgrey')
    plt.gca().add_patch(circle)
    plt.axis([-1 / u1 , 1 / u1 , -1 / u1 , 1 / u1 ])

当我切换计算机并开始使用 python 3.7 时,相同的代码开始生成一个取消配置的图片。为什么会发生这种情况,我该如何解决?前后照片如下。

【问题讨论】:

    标签: python matplotlib graph axes


    【解决方案1】:

    您的代码正在创建两个重叠的轴(正如您在第二张图片中的红色圆圈中指出的那样)。您也可以通过在代码末尾运行以下几行来看到这一点:

    print(plt.gcf().get_axes()) # (get current figure)
    

    这给出了:

    [<AxesSubplot:ylabel='y(Km)'>, <AxesSubplot:>]
    

    发生这种情况是因为当您已经有一个轴时,您可以通过 ax = plt.axes() 行添加另一个轴。来自documentation

    Add an axes to the current figure and make it the current axes.
    

    也许你的意思是ax = plt.gca()

    不管怎样,整理一下代码:

    import matplotlib.pyplot as plt
    from matplotlib.patches import Circle
    
    u1 = 0.05
    
    fig, ax = plt.subplots() # figure fig with one axes object ax
    ax.set_facecolor("black")
    ax.set_aspect("equal")
    circle = Circle((0, 0), 2, color='dimgrey')
    ax.add_patch(circle)
    ax.set_xlim([-1 / u1, 1 / u1 ])
    ax.set_ylim([-1 / u1, 1 / u1 ])
    ax.set_ylabel("y (km)")
    
    print(fig.get_axes()) # not needed for anything, just for comparison with original code
    
    plt.show()
    

    应该给出:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-22
      • 1970-01-01
      • 1970-01-01
      • 2018-12-15
      • 2016-01-22
      相关资源
      最近更新 更多