Matplotlib 全面使用指南 -- 紧密布局指南 Tight layout guide
文中内容仅限技术学习与代码实践参考,市场存在不确定性,技术分析需谨慎验证,不构成任何投资建议。
紧密布局指南
如何使用紧密布局(tight-layout)将绘图干净地适配到图形中。
提示:tight_layout 是 Matplotlib 中第一个布局引擎。现在更现代、功能更强大的 受约束布局 通常应被优先使用。
tight_layout 会自动调整子图参数,使子图(们)适配到图形区域。这是一个实验性功能,在某些情况下可能无法正常工作。它仅检查刻度标签、轴标签和标题的范围。
简单示例
使用默认的坐标轴定位时,坐标轴标题、轴标签或刻度标签有时会超出图形区域,从而被裁剪。
import matplotlib.pyplot as plt
import numpy as npplt.rcParams['savefig.facecolor'] = "0.8"def example_plot(ax, fontsize=12):ax.plot([1, 2])ax.locator_params(nbins=3)ax.set_xlabel('x-label', fontsize=fontsize)ax.set_ylabel('y-label', fontsize=fontsize)ax.set_title('Title', fontsize=fontsize)plt.close('all')
fig, ax = plt.subplots()
example_plot(ax, fontsize=24)
为了防止这种情况,需要调整坐标轴的位置。对于子图,可以通过使用 Figure.subplots_adjust
手动调整子图参数来完成。Figure.tight_layout
会自动完成此操作。
fig, ax = plt.subplots()
example_plot(ax, fontsize=24)
plt.tight_layout()
请注意,matplotlib.pyplot.tight_layout()
仅在调用时才会调整子图参数。为了在每次重绘图形时都执行此调整,可以调用 fig.set_tight_layout(True)
,或者等效地,将 rcParams["figure.autolayout"]
(默认为 False
)设置为 True
。
当您有多个子图时,经常会看到不同坐标轴的标签相互重叠。
plt.close('all')fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2)
example_plot(ax1)
example_plot(ax2)
example_plot(ax3)
example_plot(ax4)
tight_layout()
还会调整子图之间的间距,以最小化重叠。
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2)
example_plot(ax1)
example_plot(ax2)
example_plot(ax3)
example_plot(ax4)
plt.tight_layout()
tight_layout()
可以接受关键字参数 pad、w_pad 和 h_pad。这些参数控制图形边框周围以及子图之间的额外填充。填充以字体大小的分数形式指定。
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2)
example_plot(ax1)
example_plot(ax2)
example_plot(ax3)
example_plot(ax4)
plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0)
只要子图的网格规范兼容,tight_layout()
即使子图大小不同也能正常工作。在下面的示例中,ax1 和 ax2 是 2x2 网格的子图,而 ax3 是 1x2 网格的子图。
plt.close('all')
fig = plt.figure()ax1 = plt.subplot(221)
ax2 = plt.subplot(223)
ax3 = plt.subplot(122)example_plot(ax1)
example_plot(ax2)
example_plot(ax3)plt.tight_layout()
它与使用 subplot2grid()
创建的子图一起工作。通常,从 gridspec(在图形中排列多个坐标轴)创建的子图都能工作。
plt.close('all')
fig = plt.figure()ax1 = plt.subplot2grid((3, 3), (0, 0))
ax2 = plt.subplot2grid((3, 3), (0, 1), colspan=2)
ax3 = plt.subplot2grid((3, 3), (1, 0), colspan=2, rowspan=2)
ax4 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)example_plot(ax1)
example_plot(ax2)
example_plot(ax3)
example_plot(ax4)plt.tight_layout()
虽然没有经过彻底测试,但它似乎适用于 aspect != “auto” 的子图(例如,带有图像的坐标轴)。
arr = np.arange(100).reshape((10, 10))plt.close('all')
fig = plt.figure(figsize=(5, 4))ax = plt.subplot()
im = ax.imshow(arr, interpolation="none")plt.tight_layout()
注意事项
-
tight_layout
默认会考虑坐标轴上的所有艺术家(artists)。若要从布局计算中移除某个艺术家,可以调用Artist.set_in_layout
。 -
tight_layout
假设艺术家所需的额外空间与坐标轴的原始位置无关。这通常是正确的,但在极少数情况下并非如此。 -
pad=0
可能会使某些文本被裁剪几个像素。这可能是当前算法的一个错误或限制,目前尚不清楚为什么会发生这种情况。同时,建议使用大于 0.3 的 pad。 -
tight_layout
的算法不一定收敛,即多次调用tight_layout
可能会导致调用之间的布局略有不同。
与 GridSpec 一起使用
GridSpec 有自己的 GridSpec.tight_layout
方法(pyplot api pyplot.tight_layout
也可用)。
import matplotlib.gridspec as gridspecplt.close('all')
fig = plt.figure()gs1 = gridspec.GridSpec(2, 1)
ax1 = fig.add_subplot(gs1[0])
ax2 = fig.add_subplot(gs1[1])example_plot(ax1)
example_plot(ax2)gs1.tight_layout(fig)
您可以提供一个可选的 rect 参数,该参数指定子图将适配的边界框。坐标是标准化的图形坐标,默认为 (0, 0, 1, 1)(整个图形)。
fig = plt.figure()gs1 = gridspec.GridSpec(2, 1)
ax1 = fig.add_subplot(gs1[0])
ax2 = fig.add_subplot(gs1[1])example_plot(ax1)
example_plot(ax2)gs1.tight_layout(fig, rect=[0, 0, 0.5, 1.0])
但是,我们不建议将其用于手动构建更复杂的布局,例如在图形的左侧和右侧各有一个 GridSpec。对于这些用例,应改用嵌套的 Gridspec 或图形子图。
图例和注释
在 Matplotlib 2.2 之前,图例和注释被排除在决定布局的边界框计算之外。随后,这些艺术家被添加到计算中,但有时将它们包括在内并不理想。例如,在这种情况下,让坐标轴缩小一点为图例腾出空间可能是好的:
fig, ax = plt.subplots(figsize=(4, 3))
lines = ax.plot(range(10), label='A simple plot')
ax.legend(bbox_to_anchor=(0.7, 0.5), loc='center left',)
fig.tight_layout()
plt.show()
然而,有时这并不理想(在使用 fig.savefig('outname.png', bbox_inches='tight')
时经常如此)。为了将图例从边界框计算中移除,我们只需将其边界 leg.set_in_layout(False)
设置,图例将被忽略。
fig, ax = plt.subplots(figsize=(4, 3))
lines = ax.plot(range(10), label='B simple plot')
leg = ax.legend(bbox_to_anchor=(0.7, 0.5), loc='center left',)
leg.set_in_layout(False)
fig.tight_layout()
plt.show()
与 AxesGrid1 一起使用
为 mpl_toolkits.axes_grid1
提供了有限的支持。
from mpl_toolkits.axes_grid1 import Gridplt.close('all')
fig = plt.figure()
grid = Grid(fig, rect=111, nrows_ncols=(2, 2),axes_pad=0.25, label_mode='L',)for ax in grid:example_plot(ax)
ax.title.set_visible(False)plt.tight_layout()
颜色条
如果您使用 Figure.colorbar
创建颜色条,只要父坐标轴也是子图,创建的颜色条就会绘制在子图中,因此 Figure.tight_layout
将起作用。
plt.close('all')
arr = np.arange(100).reshape((10, 10))
fig = plt.figure(figsize=(4, 4))
im = plt.imshow(arr, interpolation="none")plt.colorbar(im)plt.tight_layout()
另一个选择是使用 AxesGrid1 工具包显式为颜色条创建一个坐标轴。
from mpl_toolkits.axes_grid1 import make_axes_locatableplt.close('all')
arr = np.arange(100).reshape((10, 10))
fig = plt.figure(figsize=(4, 4))
im = plt.imshow(arr, interpolation="none")divider = make_axes_locatable(plt.gca())
cax = divider.append_axes("right", "5%", pad="3%")
plt.colorbar(im, cax=cax)plt.tight_layout()
Download Jupyter notebook: tight_layout_guide.ipynb
Download Python source code: tight_layout_guide.py
Download zipped: tight_layout_guide.zip
风险提示与免责声明
本文内容基于公开信息研究整理,不构成任何形式的投资建议。历史表现不应作为未来收益保证,市场存在不可预见的波动风险。投资者需结合自身财务状况及风险承受能力独立决策,并自行承担交易结果。作者及发布方不对任何依据本文操作导致的损失承担法律责任。市场有风险,投资须谨慎。