分享

Python学习教程:Matplotlib库基础分析—自动调整函数

 千锋Python学堂 2019-11-28

今天的Python学习教程,给大家来点儿不一样的,老师敲黑板同学竖耳朵听的!

在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()

Python学习教程:Matplotlib库基础分析—自动调整函数

不过很多时候会出现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不起作用的时候,绘图效果如下所示,可见子图并没有填充整个图像区域。

Python学习教程:Matplotlib库基础分析—自动调整函数

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

Python学习教程:Matplotlib库基础分析—自动调整函数

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

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

有哪些不清楚的地方可以留言,更多的Python学习教程也会继续为大家更新!你们有想学的板块知识点也可以留言哈!

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多