python - 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 Jupyter output (note the large blank space after table)
解决方案
使用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 安装。
推荐阅读
- python - TypeError: __init__() 得到了一个意外的关键字参数“重新引用”
- python - 有哪些可能的方法来对该方法进行单元测试?
- javascript - 订阅触发后如何重新获取查询?
- javascript - 如何通过Javascript或Jquery为ul标签的li标签着色?
- go - 为什么 Regexp.ReplaceAllString 会转义替换字符串中的某些字符?
- moryx - 如何将不同的配置放入同一接口的自定义插件实现中?
- html - 提交前如何保存表单中的输入数据?
- python - 如何在 python 中使用 uber h3 将 shapefile/geojson 转换为六边形?
- python - 作为应用程序在本地运行全栈烧瓶应用程序
- python - 重复捕获组