首页 > 解决方案 > PyCharm 中的 matplotlib.pyplot.show() 移动了我的坐标轴!我怎样才能防止这种情况?

问题描述

当我在 matplot lib 中创建一个图形并使用 matplotlib.pyplot.show() 在 PyCharm 中渲染该图形时,该图形移动了!

这不会发生在 PyCharm 之外的 show()ing 中。

import matplotlib.pyplot as plt    

def axes_position_test():
    """Witness change in position after plt.show()."""
    fig = plt.figure()
    ax1 = fig.add_subplot(111)

    # original position
    print(ax1.get_position())

    plt.show()

    # position has changed
    print(ax1.get_position())

axes_position_test()
# output
# Bbox(x0=0.125, y0=0.10999999999999999, x1=0.9, y1=0.88)
# Bbox(x0=0.07300347222222223, y0=0.08067129629629632, x1=0.959375, y1=0.9572916666666668)

标签: pythonmatplotlibpycharm

解决方案


我无法重现该问题 - 代码导致我运行 matplotlib 3.0.2 时出错。也许正在使用不同的版本?

无论如何,一般要回答这个问题:
位置可能会随着时间而改变,特别是如果图形显示在图形用户界面中,图形用户界面本身可能(稍微)改变图形大小。

这个问题并不清楚最终目标,但正如我所解释的那样,目标是让两个轴相互重叠。这很容易通过

fig = plt.figure()
ax1 = fig.add_subplot(111, label="first axes")
ax2 = fig.add_subplot(111, label="second axes")

可以使用 制作更复杂的几何图形gridspec,始终使用add_subplot添加子图。

从 OP 编辑​​:正如评论中所揭示的,PyCharm 渲染器 interagg 是问题所在。禁用 interagg(设置 > 工具 > Python Scientific > 取消选中“显示绘图”)可以解决问题。


推荐阅读