使用 backend_pdf PdfPages 保存 matplotib table 时无法在 PDF 页面上居中 table

Cannot center table on PDF-page when saving a matplotib table using backend_pdf PdfPages

我可以在 jupyter notebook 中生成一个 matplotlib table(没有任何明显关联的图),但是当我尝试使用 matplotlib 的内部 backend_pdf.PdfPages 包装器将其保存为 PDF 时,它从未出现以页面为中心。

我试过弄乱 'top''center''bottom'、偏移和 savefig(pad_inches) 但无济于事。这是我的例子:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages

col_names = ["this", "that","the other","4","5","6"]
page_data = np.random.randint(100, size=(40,6))

# stringify numbers: tables can't have ints in them.
for idx, sub in enumerate(page_data):
    page_data[idx] = [str(i) for i in sub]

fig, axs = plt.subplots(1, figsize=(10,8))
axs.axis('off')
_table = plt.table(
    cellText=page_data,
    colLabels=col_names,
    loc='top',
    edges='open',
    colLoc='right')

# and now, the PDF doesn't fit on page    
pdf = PdfPages('test.pdf')
pdf.savefig(fig)
pdf.close()

我的直觉是,还有一个看不见的身影占据着 space,它正在推高我页面上的所有内容。我如何删除那个数字,或者将它的大小调整为零并且只对 table 文本进行 PDF 处理?

PDF输出截图:

Jupyter 输出截图(注意 table 后的大空白 space)

使用 loc='center' 应该可以解决这个问题,对于有问题的最小示例,

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages

col_names = ["this", "that","the other","4","5","6"]
data = np.random.randint(100, size=(40,6)).astype('str')

fig, ax = plt.subplots(1, figsize=(10,10))
ax.axis('off')
_table = plt.table(cellText=data, colLabels=col_names, 
                   loc='center', edges='open', colLoc='right')

pdf = PdfPages('test.pdf')
pdf.savefig(fig)
pdf.close()

但是请务必注意,这会将 table 定位在 'center' 中相对于当前 Axes 实例。如果您使用多个子图,使用 matplotlib.axes.Axes.table 版本可能更安全,因为它可以更好地控制使用哪个 Axes


注意 - 我已经在 Matplotlib 2.2.5 和 3.2.1 中对此进行了测试,如果上面的代码确实产生了我显示的结果,请考虑更新您的 Matplotlib 安装。