首页 > 解决方案 > Cannot center table on PDF-page when saving a matplotib table using backend_pdf PdfPages

问题描述

I can generate a matplotlib table (without any visibly associated plot) in a jupyter notebook, but when I try to save it to a PDF using matplotlib's internal backend_pdf.PdfPages wrapper, it never appears centered on a page.

I've tried messing with 'top','center','bottom', and offsets and savefig(pad_inches) to no avail. Here's my example:

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

My intuition is that there is still an invisible figure taking up space, and that's pushing up all the content on my page. How do I obliterate that figure, or size it to zero and only PDF the table text?

screenshot of PDF output: enter image description here

screenshot of Jupyter output (note the large blank space after table) enter image description here

标签: pythonmatplotlibpdfpdfpages

解决方案


使用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()

在此处输入图像描述

然而,重要的是要注意,这会将表格定位在相对于当前Axes实例的“中心”。matplotlib.axes.Axes.table如果您使用多个子图,则使用该版本可能更安全,因为它允许更好地控制使用哪个子图Axes


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


推荐阅读