模型训练时报错疑惑 UserWarning: This figure includes Axes that are not compatible with tight_layout, so results might be incorrect. self.figure.tight_layout()


参考:https://www.imooc.com/article/296147

Matplotlib库基础分析——自动调整函数tight_layout()

 

matplotlib中,轴Axes的位置以标准化图形坐标指定,可能发生的情况是轴标签、标题、刻度标签等等会超出图形区域,导致显示不全。Matplotlib v1.1 引入了一个新的命令tight_layout(),作用是自动调整子图参数,使之填充整个图像区域。

调用plt.show()函数时会自动运行tight_layout()函数,如下所示:

def show(self): self.figure.tight_layout() FigureCanvasAgg.draw(self) if PORT is None: return if matplotlib.__version__ < '1.2': buffer = self.tostring_rgb(0, 0) else: buffer = self.tostring_rgb() if len(set(buffer)) <= 1: # do not plot empty return render = self.get_renderer() width = int(render.width) plot_index = index if os.getenv("PYCHARM_MATPLOTLIB_INTERACTIVE", False) else -1 try: sock = socket.socket() sock.connect((HOST, PORT)) sock.send(struct.pack('>i', width)) sock.send(struct.pack('>i', plot_index)) sock.send(struct.pack('>i', len(buffer))) sock.send(buffer) except OSError as _: # nothing bad. It just means, that our tool window doesn't run yet pass 

我们通过以下一个例程来介绍,最终的显示效果如下所示:

fig = plt.figure(figsize=(12, 8)) ax1 = fig.add_subplot(211) ax2 = fig.add_subplot(212) ax1.plot(np.arange(10), np.random.randint(0, 10, 10), ls='-', c='r', lw=1) ax2.plot(np.arange(10), np.random.randint(10, 20, 10), ls='-', c='y', lw=1) plt.show() 

图片描述

不过很多时候会出现tight_layout()不工作的情况,比如出现以下提示:
UserWarning: This figure includes Axes that are not compatible with tight_layout, so results might be incorrect. warnings.warn("This figure includes Axes that are not compatible "
这个警告的原因是tight_layout这个函数出错了,警告语句出现的原因时axes列表为空,tight_layout()中相应的代码,如下所示:

subplotspec_list = get_subplotspec_list(self.axes) if None in subplotspec_list: cbook._warn_external("This figure includes Axes that are not " "compatible with tight_layout, so results " "might be incorrect.") 

可见这个函数并不太稳定。tight_layout不起作用的时候,绘图效果如下所示,可见子图并没有填充整个图像区域。

图片描述

网上搜索了下发现也有类似的情况出现,附上部分案例的截图:

图片描述

接下来我们尝试下解决方法,tight_layout在plt.savefig的调用方式相对比较稳定,我们将plt.show()函数替换为plt.savefig函数,替换后会在本地另外为png图片,该图片中子图填充了整个图像区域。

plt.savefig('fig.png', bbox_inches='tight') # 替换 plt.show() 

·····························
欢迎大家订阅《教你用 Python 进阶量化交易》专栏!

 

本文首次发布于慕课网 ,转载请注明出处,谢谢合作

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM